예제 #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)
}
예제 #2
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)
	}
}