github.com/wanliu/go-oauth2-server@v0.0.0-20180817021415-f928fa1580df/oauth/authorization_code.go (about) 1 package oauth 2 3 import ( 4 "errors" 5 "time" 6 7 "github.com/wanliu/go-oauth2-server/models" 8 ) 9 10 var ( 11 // ErrAuthorizationCodeNotFound ... 12 ErrAuthorizationCodeNotFound = errors.New("Authorization code not found") 13 // ErrAuthorizationCodeExpired ... 14 ErrAuthorizationCodeExpired = errors.New("Authorization code expired") 15 ) 16 17 // GrantAuthorizationCode grants a new authorization code 18 func (s *Service) GrantAuthorizationCode(client *models.OauthClient, user *models.OauthUser, expiresIn int, redirectURI, scope string) (*models.OauthAuthorizationCode, error) { 19 // Create a new authorization code 20 authorizationCode := models.NewOauthAuthorizationCode(client, user, expiresIn, redirectURI, scope) 21 if err := s.db.Create(authorizationCode).Error; err != nil { 22 return nil, err 23 } 24 authorizationCode.Client = client 25 authorizationCode.User = user 26 27 return authorizationCode, nil 28 } 29 30 // getValidAuthorizationCode returns a valid non expired authorization code 31 func (s *Service) getValidAuthorizationCode(code, redirectURI string, client *models.OauthClient) (*models.OauthAuthorizationCode, error) { 32 // Fetch the auth code from the database 33 authorizationCode := new(models.OauthAuthorizationCode) 34 notFound := models.OauthAuthorizationCodePreload(s.db).Where("client_id = ?", client.ID). 35 Where("code = ?", code).First(authorizationCode).RecordNotFound() 36 37 // Not found 38 if notFound { 39 return nil, ErrAuthorizationCodeNotFound 40 } 41 42 // Redirect URI must match if it was used to obtain the authorization code 43 if redirectURI != authorizationCode.RedirectURI.String { 44 return nil, ErrInvalidRedirectURI 45 } 46 47 // Check the authorization code hasn't expired 48 if time.Now().After(authorizationCode.ExpiresAt) { 49 return nil, ErrAuthorizationCodeExpired 50 } 51 52 return authorizationCode, nil 53 }