ResourceOwnerPasswordGrant implements the password grant type flow
(ctx context.Context, w http.ResponseWriter, r *http.Request)
| 48 | |
| 49 | // ResourceOwnerPasswordGrant implements the password grant type flow |
| 50 | func (a *API) ResourceOwnerPasswordGrant(ctx context.Context, w http.ResponseWriter, r *http.Request) error { |
| 51 | username := r.FormValue("username") |
| 52 | password := r.FormValue("password") |
| 53 | cookie := r.Header.Get(useCookieHeader) |
| 54 | |
| 55 | aud := a.requestAud(ctx, r) |
| 56 | instanceID := getInstanceID(ctx) |
| 57 | config := a.getConfig(ctx) |
| 58 | |
| 59 | user, err := models.FindUserByEmailAndAudience(a.db, instanceID, username, aud) |
| 60 | if err != nil { |
| 61 | if models.IsNotFoundError(err) { |
| 62 | return oauthError("invalid_grant", "No user found with that email, or password invalid.") |
| 63 | } |
| 64 | return internalServerError("Database error finding user").WithInternalError(err) |
| 65 | } |
| 66 | |
| 67 | if !user.IsConfirmed() { |
| 68 | return oauthError("invalid_grant", "Email not confirmed") |
| 69 | } |
| 70 | |
| 71 | if !user.Authenticate(password) { |
| 72 | return oauthError("invalid_grant", "No user found with that email, or password invalid.") |
| 73 | } |
| 74 | |
| 75 | var token *AccessTokenResponse |
| 76 | err = a.db.Transaction(func(tx *storage.Connection) error { |
| 77 | var terr error |
| 78 | if terr = models.NewAuditLogEntry(tx, instanceID, user, models.LoginAction, nil); terr != nil { |
| 79 | return terr |
| 80 | } |
| 81 | if terr = triggerEventHooks(ctx, tx, LoginEvent, user, instanceID, config); terr != nil { |
| 82 | return terr |
| 83 | } |
| 84 | |
| 85 | token, terr = a.issueRefreshToken(ctx, tx, user) |
| 86 | if terr != nil { |
| 87 | return terr |
| 88 | } |
| 89 | |
| 90 | if cookie != "" && config.Cookie.Duration > 0 { |
| 91 | if terr = a.setCookieToken(config, token.Token, cookie == useSessionCookie, w); terr != nil { |
| 92 | return internalServerError("Failed to set JWT cookie. %s", terr) |
| 93 | } |
| 94 | } |
| 95 | return nil |
| 96 | }) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | metering.RecordLogin("password", user.ID, instanceID) |
| 101 | return sendJSON(w, http.StatusOK, token) |
| 102 | } |
| 103 | |
| 104 | // RefreshTokenGrant implements the refresh_token grant type flow |
| 105 | func (a *API) RefreshTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.Request) error { |
no test coverage detected