github.com/resonatecoop/id@v1.1.0-43/oauth/authorization_code.go (about) 1 package oauth 2 3 import ( 4 "context" 5 "errors" 6 "time" 7 8 "github.com/resonatecoop/user-api/model" 9 ) 10 11 var ( 12 // ErrAuthorizationCodeNotFound ... 13 ErrAuthorizationCodeNotFound = errors.New("Authorization code not found") 14 // ErrAuthorizationCodeExpired ... 15 ErrAuthorizationCodeExpired = errors.New("Authorization code expired") 16 ) 17 18 // GrantAuthorizationCode grants a new authorization code 19 func (s *Service) GrantAuthorizationCode(client *model.Client, user *model.User, expiresIn int, redirectURI, scope string) (*model.AuthorizationCode, error) { 20 // Create a new authorization code 21 authorizationCode := model.NewOauthAuthorizationCode(client, user, expiresIn, redirectURI, scope) 22 23 ctx := context.Background() 24 25 _, err := s.db.NewInsert().Model(authorizationCode).Exec(ctx) 26 if err != nil { 27 return nil, err 28 } 29 authorizationCode.Client = client 30 authorizationCode.User = user 31 32 return authorizationCode, nil 33 } 34 35 // getValidAuthorizationCode returns a valid non expired authorization code 36 func (s *Service) getValidAuthorizationCode(code, redirectURI string, client *model.Client) (*model.AuthorizationCode, error) { 37 // Fetch the auth code from the database 38 ctx := context.Background() 39 authorizationCode := new(model.AuthorizationCode) 40 41 err := s.db.NewSelect(). 42 Model(authorizationCode). 43 Where("client_id = ?", client.ID). 44 Where("code = ?", code). 45 Limit(1). 46 Scan(ctx) 47 48 // Not Found! 49 if err != nil { 50 return nil, ErrAuthorizationCodeNotFound 51 } 52 53 authorizationCode.Client = client 54 55 user := new(model.User) 56 57 err = s.db.NewSelect(). 58 Model(user). 59 Where("id = ?", authorizationCode.UserID). 60 Limit(1). 61 Scan(ctx) 62 63 // Not Found! 64 if err != nil { 65 return nil, errors.New("corresponding user for authorization code not found") 66 } 67 68 authorizationCode.User = user 69 70 // Redirect URI must match if it was used to obtain the authorization code 71 if redirectURI != authorizationCode.RedirectURI.String { 72 return nil, ErrInvalidRedirectURI 73 } 74 75 // Check the authorization code hasn't expired 76 if time.Now().After(authorizationCode.ExpiresAt) { 77 return nil, ErrAuthorizationCodeExpired 78 } 79 80 return authorizationCode, nil 81 }