| 160 | } |
| 161 | |
| 162 | func (h *Handler) CreateClient(r *http.Request, validator func(context.Context, *Client) error, isDynamic bool) (*Client, error) { |
| 163 | var c Client |
| 164 | if err := json.NewDecoder(r.Body).Decode(&c); err != nil { |
| 165 | return nil, errors.WithStack(herodot.ErrBadRequest.WithReasonf("Unable to decode the request body: %s", err)) |
| 166 | } |
| 167 | |
| 168 | if isDynamic { |
| 169 | if c.Secret != "" { |
| 170 | return nil, errors.WithStack(herodot.ErrBadRequest.WithReasonf("It is not allowed to choose your own OAuth2 Client secret.")) |
| 171 | } |
| 172 | // We do not allow to set the client ID for dynamic clients. |
| 173 | c.ID = uuidx.NewV4().String() |
| 174 | } |
| 175 | |
| 176 | if len(c.Secret) == 0 { |
| 177 | secretb, err := x.GenerateSecret(26) |
| 178 | if err != nil { |
| 179 | return nil, err |
| 180 | } |
| 181 | c.Secret = string(secretb) |
| 182 | } |
| 183 | |
| 184 | if err := validator(r.Context(), &c); err != nil { |
| 185 | return nil, err |
| 186 | } |
| 187 | |
| 188 | secret := c.Secret |
| 189 | c.CreatedAt = time.Now().UTC().Round(time.Second) |
| 190 | c.UpdatedAt = c.CreatedAt |
| 191 | |
| 192 | token, signature, err := h.r.OAuth2HMACStrategy().GenerateAccessToken(r.Context(), nil) |
| 193 | if err != nil { |
| 194 | return nil, err |
| 195 | } |
| 196 | |
| 197 | c.RegistrationAccessToken = token |
| 198 | c.RegistrationAccessTokenSignature = signature |
| 199 | c.RegistrationClientURI = urlx.AppendPaths(h.r.Config().PublicURL(r.Context()), DynClientsHandlerPath, url.PathEscape(c.GetID())).String() |
| 200 | |
| 201 | if err := h.r.ClientManager().CreateClient(r.Context(), &c); err != nil { |
| 202 | return nil, err |
| 203 | } |
| 204 | c.Secret = "" |
| 205 | if !c.IsPublic() { |
| 206 | c.Secret = secret |
| 207 | } |
| 208 | return &c, nil |
| 209 | } |
| 210 | |
| 211 | // Set OAuth 2.0 Client Parameters |
| 212 | // |