示例#1
0
// LoginWithClientID logs a user in using the data from the client, which
// gives them permission to post a question, comment, and vote in a group
func (handler UserHandler) LoginWithClientID(c *gin.Context) {
	// deserialize post
	var userReq req.UserRequest
	if err := c.BindJSON(&userReq); err != nil {
		log.Printf("Unable to parse user: %s", err)
		c.JSON(http.StatusBadRequest, resp.APIResponse{IsError: true, Message: "Insufficient data"})
		return
	}
	if !userReq.IsValid() {
		c.JSON(http.StatusBadRequest, resp.APIResponse{IsError: true, Message: "Invalid data"})
		return
	}

	// create user object from request
	user := userReq.ToUser()

	// create or get user from db
	if err := handler.db.FirstOrCreate(&user, table.User{ClientID: user.ClientID}).Error; err != nil {
		c.JSON(http.StatusBadRequest, resp.APIResponse{IsError: true, Message: "Error logging in"})
		return
	}

	// set user logged in
	auth.StoreUserIDInCookie(c, user.ID)

	c.JSON(http.StatusOK, resp.APIResponse{IsError: false, Value: user})
}
示例#2
0
// Login attempts to log an admin in
func (handler AdminHandler) Login(c *gin.Context) {
	var userReq req.AdminLoginRequest
	if err := c.BindJSON(&userReq); err != nil {
		log.Printf("Unable to parse user: %s", err)
		c.JSON(http.StatusBadRequest, resp.APIResponse{IsError: true, Message: "Error logging in"})
		return
	}

	// create user object from request
	user := userReq.ToUser()

	// lookup user in db
	// TODO user passwords should be hashed
	if err := handler.db.First(&user, table.User{Email: user.Email, Password: user.Password}).Error; err != nil {
		c.JSON(http.StatusBadRequest, resp.APIResponse{IsError: true, Message: "Email or password is incorrect"})
		return
	}

	if !auth.HasAccessToGroup(user.ID, userReq.GroupUUID, handler.db) {
		c.JSON(http.StatusForbidden, resp.APIResponse{IsError: true, Message: "You don't have permission to access this group"})
		return
	}

	// set user logged in
	auth.StoreUserIDInCookie(c, user.ID)

	c.JSON(http.StatusOK, resp.APIResponse{IsError: false, Value: user})
}