Auth @Tags sessions @Summary User Login @Description User Login @Accept json @Produce json @Param request body LoginCredential true "request" @Router /sessions [post]
()
| 187 | // @Param request body LoginCredential true "request" |
| 188 | // @Router /sessions [post] |
| 189 | func (h *Handler) Login() iris.Handler { |
| 190 | return func(ctx *context.Context) { |
| 191 | var loginCredential LoginCredential |
| 192 | if err := ctx.ReadJSON(&loginCredential); err != nil { |
| 193 | ctx.StatusCode(iris.StatusBadRequest) |
| 194 | ctx.Values().Set("message", err.Error()) |
| 195 | return |
| 196 | } |
| 197 | u, err := h.userService.GetByNameOrEmail(loginCredential.Username, common.DBOptions{}) |
| 198 | if err != nil { |
| 199 | if errors.Is(err, storm.ErrNotFound) { |
| 200 | ctx.StatusCode(iris.StatusBadRequest) |
| 201 | ctx.Values().Set("message", "username or password error") |
| 202 | return |
| 203 | } |
| 204 | ctx.StatusCode(iris.StatusInternalServerError) |
| 205 | ctx.Values().Set("message", fmt.Sprintf("query user %s failed ,: %s", loginCredential.Username, err.Error())) |
| 206 | return |
| 207 | } |
| 208 | |
| 209 | switch u.Type { |
| 210 | case v1User.LDAP: |
| 211 | if !h.ldapService.CheckStatus() { |
| 212 | ctx.StatusCode(iris.StatusInternalServerError) |
| 213 | ctx.Values().Set("message", "ldap is not enable!") |
| 214 | return |
| 215 | } |
| 216 | if err := h.ldapService.Login(*u, loginCredential.Password, common.DBOptions{}); err != nil { |
| 217 | ctx.StatusCode(iris.StatusInternalServerError) |
| 218 | ctx.Values().Set("message", "username or password error") |
| 219 | return |
| 220 | } |
| 221 | case "", v1User.LOCAL: |
| 222 | if err := bcrypt.CompareHashAndPassword([]byte(u.Authenticate.Password), []byte(loginCredential.Password)); err != nil { |
| 223 | ctx.StatusCode(iris.StatusBadRequest) |
| 224 | ctx.Values().Set("message", "username or password error") |
| 225 | return |
| 226 | } |
| 227 | default: |
| 228 | ctx.StatusCode(iris.StatusBadRequest) |
| 229 | ctx.Values().Set("message", "username or password error") |
| 230 | return |
| 231 | } |
| 232 | |
| 233 | profile, err := h.buildUserProfile(u, false) |
| 234 | if err != nil { |
| 235 | ctx.StatusCode(iris.StatusInternalServerError) |
| 236 | ctx.Values().Set("message", err.Error()) |
| 237 | return |
| 238 | } |
| 239 | |
| 240 | authMethod := loginCredential.AuthMethod |
| 241 | |
| 242 | switch authMethod { |
| 243 | case "jwt": |
| 244 | if profile.Mfa.Enable { |
| 245 | ctx.StatusCode(iris.StatusUnauthorized) |
| 246 | ctx.Values().Set("message", "mfa is required") |
no test coverage detected