ActivityPub/entities/user/userController.go

104 lines
2.5 KiB
Go
Raw Normal View History

2020-10-17 10:13:15 +00:00
package user
import (
"encoding/json"
"fmt"
"net/http"
"git.nutfactory.org/hoernschen/ActivityPub/entities/actor"
"git.nutfactory.org/hoernschen/ActivityPub/utils"
)
func New(id string, password string) (err error, newUser *User) {
err, hashedPassword := utils.Hash([]byte(password))
if err != nil {
return
}
newUser = &User{
Id: id,
Password: hashedPassword,
}
return
}
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
request := RegisterRequest{}
err := utils.CheckRequest(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
return
}
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&request)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode("Could not parse JSON: %s"); err != nil {
panic(err)
}
return
}
err, newUser := New(request.Username, request.Password)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(fmt.Sprintf("Error creating User Object: %s")); err != nil {
panic(err)
}
return
}
foundUser, err := ReadUser(newUser.Id)
if foundUser != nil || err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(fmt.Sprintf("Username already in use: %s", err)); err != nil {
panic(err)
}
return
}
newActor := actor.New(newUser.Id)
err = actor.CreateActor(newActor)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(fmt.Sprintf("Database Error Creating Actor: %s")); err != nil {
panic(err)
}
return
}
newUser.Actor = newActor.Id
err = CreateUser(newUser)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode("Database Error Creating User: %s"); err != nil {
panic(err)
}
return
}
err, token := utils.CreateToken()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode("Error Creating Token: %s"); err != nil {
panic(err)
}
return
}
err = CreateSession(newUser.Id, token)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode("Error Creating Session: %s"); err != nil {
panic(err)
}
return
}
response := RegisterResponse{
UserId: newUser.Id,
Token: token,
Actor: newActor.Id,
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
panic(err)
}
}