| 61 | |
| 62 | func AuthorizeCreate(env *activitypub.Env, w http.ResponseWriter, r *http.Request) error { |
| 63 | var params struct { |
| 64 | Username string `json:"-" schema:"username,required"` |
| 65 | Password string `json:"-" schema:"password,required"` |
| 66 | RedirectURI string `json:"-" schema:"redirect_uri,required"` |
| 67 | ClientID string `json:"-" schema:"client_id,required"` |
| 68 | ResponseType string `json:"-" schema:"response_type"` // ignored |
| 69 | } |
| 70 | if err := httpx.Params(r, ¶ms); err != nil { |
| 71 | return err |
| 72 | } |
| 73 | |
| 74 | var app models.Application |
| 75 | if err := env.DB.Where("client_id = ?", params.ClientID).First(&app).Error; err != nil { |
| 76 | return httpx.Error(http.StatusBadRequest, fmt.Errorf("failed to find application: %v", err)) |
| 77 | } |
| 78 | |
| 79 | var account models.Account |
| 80 | if err := env.DB.Joins("Actor").First(&account, "name = ? and domain = ?", params.Username, r.Host).Error; err != nil { |
| 81 | return httpx.Error(http.StatusUnauthorized, fmt.Errorf("invalid username")) |
| 82 | } |
| 83 | |
| 84 | if err := bcrypt.CompareHashAndPassword(account.EncryptedPassword, []byte(params.Password)); err != nil { |
| 85 | return httpx.Error(http.StatusUnauthorized, fmt.Errorf("invalid password")) |
| 86 | } |
| 87 | |
| 88 | token := &models.Token{ |
| 89 | AccessToken: uuid.New().String(), |
| 90 | AccountID: &account.ID, |
| 91 | ApplicationID: app.ID, |
| 92 | TokenType: models.TokenType("Bearer"), |
| 93 | Scope: "read write follow push", |
| 94 | AuthorizationCode: uuid.New().String(), |
| 95 | } |
| 96 | if err := env.DB.Create(token).Error; err != nil { |
| 97 | return err |
| 98 | } |
| 99 | |
| 100 | if params.RedirectURI == "" { |
| 101 | params.RedirectURI = app.RedirectURI |
| 102 | } |
| 103 | |
| 104 | return httpx.Redirect(w, params.RedirectURI+"?code="+token.AuthorizationCode) |
| 105 | } |
| 106 | |
| 107 | func TokenCreate(env *activitypub.Env, w http.ResponseWriter, r *http.Request) error { |
| 108 | var params struct { |
| 109 | ClientID string `json:"client_id" schema:"client_id,required"` |