Generating token using keycloak
[nonrtric/plt/sme.git] / capifcore / internal / securityapi / typevalidation.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2023: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package securityapi
22
23 import (
24         "strings"
25 )
26
27 func (tokenReq AccessTokenReq) Validate() (bool, AccessTokenErr) {
28
29         if tokenReq.ClientId == "" {
30                 return false, createAccessTokenError(AccessTokenErrErrorInvalidRequest, "Invalid request")
31         }
32
33         if tokenReq.GrantType != AccessTokenReqGrantTypeClientCredentials {
34                 return false, createAccessTokenError(AccessTokenErrErrorInvalidGrant, "Invalid value for grant_type")
35         }
36
37         //3gpp#aefId1:apiName1,apiName2,…apiNameX;aefId2:apiName1,apiName2,…apiNameY;…aefIdN:apiName1,apiName2,…apiNameZ
38         if tokenReq.Scope != nil && *tokenReq.Scope != "" {
39                 scope := strings.Split(*tokenReq.Scope, "#")
40                 if len(scope) < 2 {
41                         return false, createAccessTokenError(AccessTokenErrErrorInvalidScope, "Malformed scope")
42                 }
43                 if scope[0] != "3gpp" {
44                         return false, createAccessTokenError(AccessTokenErrErrorInvalidScope, "Scope should start with 3gpp")
45                 }
46                 aefList := strings.Split(scope[1], ";")
47                 for _, aef := range aefList {
48                         apiList := strings.Split(aef, ":")
49                         if len(apiList) < 2 {
50                                 return false, createAccessTokenError(AccessTokenErrErrorInvalidScope, "Malformed scope")
51                         }
52                 }
53         }
54         return true, AccessTokenErr{}
55 }
56
57 func createAccessTokenError(err AccessTokenErrError, message string) AccessTokenErr {
58         return AccessTokenErr{
59                 Error:            err,
60                 ErrorDescription: &message,
61         }
62 }