Example #1
0
func login(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	req := loginReq{}

	if err := util.ParseJSON(r.Body, w, &req); err != nil {
		// ParseJSON handles error reponse
		return
	}

	user, err := models.GetUser("", req.Email)

	if err != nil {
		logger.Debug.Println("User not found")
		util.JSONResponse(w, incorectEmailOrPassword, 401)
		return
	}

	if !user.CheckPass(req.Password) {
		logger.Debug.Println("Incorrect Password")
		util.JSONResponse(w, incorectEmailOrPassword, 401)
		return
	}

	token, err := userToken.New(user.ID, time.Now().Add(userTokenExp))

	if err != nil {
		logger.Error.Print(err)
		w.WriteHeader(500)
		return
	}

	util.JSONResponse(w, loginRes{Token: token}, 200)
}
Example #2
0
func updateUser(w http.ResponseWriter, r *http.Request, u *models.User) {
	defer r.Body.Close()

	req := registerReq{}

	if err := util.ParseJSON(r.Body, w, &req); err != nil {
		return
	}

	msg, err := u.Update(req.Email, req.Password)

	if err != nil {
		w.WriteHeader(500)
		return
	}

	if len(msg) > 0 {
		util.JSONResponse(w, validate.ValidationMsgsToJSON(msg), 400)
		return
	}

	util.JSONResponse(w, u, 200)
}
Example #3
0
// CheckAuth checks authentication and
func CheckAuth(fn UserReq) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		valid, usrID := userToken.Valid(r.Header.Get("Authorization"))

		if !valid {
			util.JSONResponse(w, invalidToken, 401)
			return
		}

		usr, err := models.GetUser(usrID, "")

		if err == gorm.RecordNotFound {
			util.JSONResponse(w, invalidToken, 401)
			return
		} else if err != nil {
			logger.Error.Print(err)
			w.WriteHeader(500)
			return
		}

		fn(w, r, usr)
	}
}
Example #4
0
func register(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	req := registerReq{}

	if err := util.ParseJSON(r.Body, w, &req); err != nil {
		return
	}

	_, msg, err := models.NewUser(req.Email, req.Password)

	if err != nil {
		w.WriteHeader(500)
		return
	}

	if len(msg) > 0 {
		util.JSONResponse(w, validate.ValidationMsgsToJSON(msg), 400)
		return
	}

	w.WriteHeader(201)
}
Example #5
0
func getUser(w http.ResponseWriter, r *http.Request, u *models.User) {
	util.JSONResponse(w, u, 200)
}