示例#1
0
// RegisterHandler is a handler which create a new user in database.
// If an error occured, the handler writes a 401 error
// If all is ok, the handler writes a session token on the response
func RegisterHandler(w http.ResponseWriter, request *http.Request) {
	inputUser := decodeInput(request)
	if inputUser == nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	userExist, _ := models.CountUserByUsername(inputUser.Username)
	if userExist != 0 {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	var user models.User
	user.Username = inputUser.Username
	user.Password = encodePassword(inputUser.Password)

	id, err := models.CreateUser(&user)
	if err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	token, err := session.CreateToken(id)
	if err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	w.Write([]byte(token))
}
示例#2
0
func TestCreateToken(t *testing.T) {
	token, err := session.CreateToken(myID)
	if err != nil {
		t.Error(err)
	}
	if token != tokenAuth {
		t.Errorf("Invalid token : result [%s], expected [%s]", token, tokenAuth)
	}
}
示例#3
0
// LoginHandler creates a session token
// If an error occured, the handler sends a 401 error
func LoginHandler(w http.ResponseWriter, request *http.Request) {
	inputUser := decodeInput(request)
	if inputUser == nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	user, err := models.FindUserByUsername(inputUser.Username)
	if err != nil || encodePassword(inputUser.Password) != user.Password {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	token, err := session.CreateToken(user.ID)
	if err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	w.Write([]byte(token))
}