Example #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))
}
Example #2
0
func TestUser(t *testing.T) {

	user := models.User{
		Username: "******",
		Password: [64]byte{2, 3, 5, 7, 11, 13},
	}

	defer models.Db.Exec("DELETE FROM users")

	//Check creation
	models.CreateUser(&user)

	count, err := models.CountUsers()
	if err != nil {
		t.Errorf("Error count user: %s", err)
	}
	if count != 1 {
		t.Errorf("Number user %d != 1 : ", count)
	}

	//Check find
	user2, err := models.FindUserByUsername("test")
	if err != nil {
		t.Errorf("Error finding user: %s", err)
	}
	if user2 == nil {
		t.Errorf("User return is null")
	}
	for i := 0; i < 64; i++ {
		if user2.Password[i] != user.Password[i] {
			t.Errorf("Bad password")
			break
		}
	}

}