netmaker/controllers/userHttpController.go

549 lines
15 KiB
Go
Raw Normal View History

2021-03-26 00:17:52 +08:00
package controller
import (
2021-04-18 02:03:01 +08:00
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
2021-05-01 11:07:25 +08:00
"github.com/go-playground/validator/v10"
2021-04-18 02:03:01 +08:00
"github.com/gorilla/mux"
"github.com/gravitl/netmaker/functions"
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/mongoconn"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang.org/x/crypto/bcrypt"
2021-03-26 00:17:52 +08:00
)
func userHandlers(r *mux.Router) {
2021-04-18 02:03:01 +08:00
r.HandleFunc("/api/users/adm/hasadmin", hasAdmin).Methods("GET")
r.HandleFunc("/api/users/adm/createadmin", createAdmin).Methods("POST")
r.HandleFunc("/api/users/adm/authenticate", authenticateUser).Methods("POST")
r.HandleFunc("/api/users/{username}", authorizeUser(http.HandlerFunc(updateUser))).Methods("PUT")
2021-07-02 12:03:46 +08:00
r.HandleFunc("/api/users/{username}/adm", authorizeUserAdm(http.HandlerFunc(updateUserAdm))).Methods("PUT")
r.HandleFunc("/api/users/{username}", authorizeUserAdm(http.HandlerFunc(createUser))).Methods("POST")
2021-04-18 02:03:01 +08:00
r.HandleFunc("/api/users/{username}", authorizeUser(http.HandlerFunc(deleteUser))).Methods("DELETE")
r.HandleFunc("/api/users/{username}", authorizeUser(http.HandlerFunc(getUser))).Methods("GET")
2021-07-02 12:03:46 +08:00
r.HandleFunc("/api/users", authorizeUserAdm(http.HandlerFunc(getUsers))).Methods("GET")
2021-03-26 00:17:52 +08:00
}
//Node authenticates using its password and retrieves a JWT for authorization.
func authenticateUser(response http.ResponseWriter, request *http.Request) {
2021-04-18 02:03:01 +08:00
//Auth request consists of Mac Address and Password (from node that is authorizing
//in case of Master, auth is ignored and mac is set to "mastermac"
var authRequest models.UserAuthParams
var errorResponse = models.ErrorResponse{
Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
}
decoder := json.NewDecoder(request.Body)
decoderErr := decoder.Decode(&authRequest)
defer request.Body.Close()
if decoderErr != nil {
returnErrorResponse(response, request, errorResponse)
return
2021-04-30 06:14:13 +08:00
}
jwt, err := VerifyAuthRequest(authRequest)
if err != nil {
2021-04-30 23:30:19 +08:00
returnErrorResponse(response, request, formatError(err, "badrequest"))
return
2021-04-30 06:14:13 +08:00
}
if jwt == "" {
2021-04-30 23:30:19 +08:00
//very unlikely that err is !nil and no jwt returned, but handle it anyways.
returnErrorResponse(response, request, formatError(errors.New("No token returned"), "internal"))
2021-04-30 06:14:13 +08:00
return
}
var successResponse = models.SuccessResponse{
Code: http.StatusOK,
Message: "W1R3: Device " + authRequest.UserName + " Authorized",
Response: models.SuccessfulUserLoginResponse{
AuthToken: jwt,
UserName: authRequest.UserName,
},
}
//Send back the JWT
successJSONResponse, jsonError := json.Marshal(successResponse)
if jsonError != nil {
returnErrorResponse(response, request, errorResponse)
return
2021-03-26 00:17:52 +08:00
}
2021-04-30 06:14:13 +08:00
response.Header().Set("Content-Type", "application/json")
response.Write(successJSONResponse)
}
func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) {
var result models.User
if authRequest.UserName == "" {
return "", errors.New("Username can't be empty")
} else if authRequest.Password == "" {
return "", errors.New("Password can't be empty")
}
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
collection := mongoconn.Client.Database("netmaker").Collection("users")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
var err = collection.FindOne(ctx, bson.M{"username": authRequest.UserName}).Decode(&result)
defer cancel()
if err != nil {
return "", errors.New("User " + authRequest.UserName + " not found")
}
// This is a a useless test as cannot create user that is not an an admin
2021-07-02 12:03:46 +08:00
//if !result.IsAdmin {
// return "", errors.New("User is not an admin")
//}
2021-04-30 06:14:13 +08:00
//compare password from request to stored password in database
//might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text...
//TODO: Consider a way of hashing the password client side before sending, or using certificates
err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password))
if err != nil {
return "", errors.New("Wrong Password")
}
//Create a new JWT for the node
2021-07-02 12:03:46 +08:00
tokenString, _ := functions.CreateUserJWT(authRequest.UserName, result.Networks, result.IsAdmin)
2021-04-30 06:14:13 +08:00
return tokenString, nil
2021-03-26 00:17:52 +08:00
}
//The middleware for most requests to the API
//They all pass through here first
//This will validate the JWT (or check for master token)
//This will also check against the authNetwork and make sure the node should be accessing that endpoint,
2021-03-26 00:17:52 +08:00
//even if it's technically ok
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
//TODO: Consider better RBAC implementations
func authorizeUser(next http.Handler) http.HandlerFunc {
2021-04-18 02:03:01 +08:00
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
2021-07-02 12:03:46 +08:00
var params = mux.Vars(r)
2021-03-26 00:17:52 +08:00
//get the auth token
bearerToken := r.Header.Get("Authorization")
2021-07-02 12:03:46 +08:00
err := ValidateUserToken(bearerToken, params["username"], false)
2021-04-30 06:14:13 +08:00
if err != nil {
2021-04-30 23:30:19 +08:00
returnErrorResponse(w, r, formatError(err, "unauthorized"))
return
2021-03-26 10:29:36 +08:00
}
2021-04-30 06:14:13 +08:00
next.ServeHTTP(w, r)
}
}
2021-03-26 00:17:52 +08:00
2021-07-02 12:03:46 +08:00
func authorizeUserAdm(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
//get the auth token
bearerToken := r.Header.Get("Authorization")
err := ValidateUserToken(bearerToken, params["username"], true)
if err != nil {
returnErrorResponse(w, r, formatError(err, "unauthorized"))
return
}
next.ServeHTTP(w, r)
}
}
func ValidateUserToken(token string, user string, adminonly bool) error {
2021-04-30 06:14:13 +08:00
var tokenSplit = strings.Split(token, " ")
2021-03-26 00:17:52 +08:00
2021-04-30 06:14:13 +08:00
//I put this in in case the user doesn't put in a token at all (in which case it's empty)
//There's probably a smarter way of handling this.
var authToken = "928rt238tghgwe@TY@$Y@#WQAEGB2FC#@HG#@$Hddd"
if len(tokenSplit) > 1 {
authToken = tokenSplit[1]
} else {
return errors.New("Missing Auth Token.")
}
2021-03-26 00:17:52 +08:00
2021-07-02 12:03:46 +08:00
username, _, isadmin, err := functions.VerifyUserToken(authToken)
2021-04-30 06:14:13 +08:00
if err != nil {
return errors.New("Error Verifying Auth Token")
}
2021-07-02 12:03:46 +08:00
isAuthorized := false
if adminonly {
isAuthorized = isadmin
} else {
isAuthorized = username == user || isadmin
}
2021-04-30 06:14:13 +08:00
if !isAuthorized {
return errors.New("You are unauthorized to access this endpoint.")
2021-03-26 00:17:52 +08:00
}
2021-04-30 06:14:13 +08:00
return nil
2021-03-26 00:17:52 +08:00
}
2021-04-18 02:03:01 +08:00
func HasAdmin() (bool, error) {
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
collection := mongoconn.Client.Database("netmaker").Collection("users")
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
filter := bson.M{"isadmin": true}
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
//Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
var result bson.M
2021-03-26 00:17:52 +08:00
err := collection.FindOne(ctx, filter).Decode(&result)
2021-04-18 02:03:01 +08:00
defer cancel()
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
if err != nil {
2021-03-26 00:17:52 +08:00
if err == mongo.ErrNoDocuments {
2021-04-29 01:49:24 +08:00
return false, nil
2021-03-26 00:17:52 +08:00
}
2021-04-29 01:49:24 +08:00
return false, err
2021-03-26 00:17:52 +08:00
fmt.Println(err)
}
return true, err
}
func hasAdmin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
hasadmin, _ := HasAdmin()
//Returns all the nodes in JSON format
json.NewEncoder(w).Encode(hasadmin)
}
func GetUser(username string) (models.User, error) {
2021-04-18 02:03:01 +08:00
var user models.User
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
collection := mongoconn.Client.Database("netmaker").Collection("users")
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
filter := bson.M{"username": username}
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&user)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
defer cancel()
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
return user, err
2021-03-26 00:17:52 +08:00
}
2021-07-02 12:03:46 +08:00
func GetUsers() ([]models.User, error) {
var users []models.User
collection := mongoconn.Client.Database("netmaker").Collection("users")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
if err != nil {
return users, err
}
defer cancel()
for cur.Next(context.TODO()) {
var user models.User
err := cur.Decode(&user)
if err != nil {
return users, err
}
// add network our array
users = append(users, user)
}
if err := cur.Err(); err != nil {
return users, err
}
return users, err
}
2021-03-26 00:17:52 +08:00
//Get an individual node. Nothin fancy here folks.
func getUser(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
2021-04-18 02:03:01 +08:00
var params = mux.Vars(r)
2021-03-26 00:17:52 +08:00
user, err := GetUser(params["username"])
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
2021-03-26 00:17:52 +08:00
return
}
json.NewEncoder(w).Encode(user)
}
2021-07-02 12:03:46 +08:00
//Get an individual node. Nothin fancy here folks.
func getUsers(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
users, err := GetUsers()
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
json.NewEncoder(w).Encode(users)
}
2021-03-26 00:17:52 +08:00
func CreateUser(user models.User) (models.User, error) {
2021-04-30 06:14:13 +08:00
hasadmin, err := HasAdmin()
2021-07-02 12:03:46 +08:00
if hasadmin && user.IsAdmin {
2021-04-30 06:14:13 +08:00
return models.User{}, errors.New("Admin already Exists")
}
err = ValidateUser("create", user)
if err != nil {
return models.User{}, err
}
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
//encrypt that password so we never see it again
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5)
if err != nil {
return user, err
}
//set password to encrypted password
user.Password = string(hash)
2021-03-26 00:17:52 +08:00
2021-07-02 12:03:46 +08:00
tokenString, _ := functions.CreateUserJWT(user.UserName,user.Networks, user.IsAdmin)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
if tokenString == "" {
//returnErrorResponse(w, r, errorResponse)
return user, err
}
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
// connect db
collection := mongoconn.Client.Database("netmaker").Collection("users")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
// insert our node to the node db.
2021-04-30 06:14:13 +08:00
_, err = collection.InsertOne(ctx, user)
2021-04-18 02:03:01 +08:00
defer cancel()
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
return user, err
2021-03-26 00:17:52 +08:00
}
func createAdmin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var admin models.User
//get node from body of request
_ = json.NewDecoder(r.Body).Decode(&admin)
2021-07-02 12:03:46 +08:00
admin.IsAdmin = true
2021-04-30 06:14:13 +08:00
admin, err := CreateUser(admin)
2021-04-30 23:30:19 +08:00
2021-04-18 02:03:01 +08:00
if err != nil {
2021-04-30 23:30:19 +08:00
returnErrorResponse(w, r, formatError(err, "badrequest"))
2021-04-18 02:03:01 +08:00
return
}
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(admin)
}
2021-07-02 12:03:46 +08:00
func createUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user models.User
//get node from body of request
_ = json.NewDecoder(r.Body).Decode(&user)
user, err := CreateUser(user)
if err != nil {
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
json.NewEncoder(w).Encode(user)
}
2021-03-26 00:17:52 +08:00
func UpdateUser(userchange models.User, user models.User) (models.User, error) {
2021-04-30 06:14:13 +08:00
err := ValidateUser("update", userchange)
if err != nil {
return models.User{}, err
}
2021-04-18 02:03:01 +08:00
queryUser := user.UserName
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
if userchange.UserName != "" {
user.UserName = userchange.UserName
}
2021-07-02 12:03:46 +08:00
if len(userchange.Networks) > 0 {
user.Networks = userchange.Networks
}
2021-04-18 02:03:01 +08:00
if userchange.Password != "" {
//encrypt that password so we never see it again
hash, err := bcrypt.GenerateFromPassword([]byte(userchange.Password), 5)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
if err != nil {
return userchange, err
}
//set password to encrypted password
userchange.Password = string(hash)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
user.Password = userchange.Password
}
//collection := mongoconn.ConnectDB()
collection := mongoconn.Client.Database("netmaker").Collection("users")
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
// Create filter
filter := bson.M{"username": queryUser}
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
fmt.Println("Updating User " + user.UserName)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
// prepare update model.
update := bson.D{
{"$set", bson.D{
{"username", user.UserName},
{"password", user.Password},
2021-07-02 12:03:46 +08:00
{"networks", user.Networks},
2021-04-18 02:03:01 +08:00
{"isadmin", user.IsAdmin},
}},
}
var userupdate models.User
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&userupdate)
2021-03-26 00:17:52 +08:00
if errN != nil {
2021-04-18 02:03:01 +08:00
fmt.Println("Could not update: ")
fmt.Println(errN)
} else {
2021-03-26 00:17:52 +08:00
fmt.Println("User updated successfully.")
}
2021-04-18 02:03:01 +08:00
defer cancel()
2021-03-26 00:17:52 +08:00
2021-04-30 06:14:13 +08:00
return user, errN
2021-03-26 00:17:52 +08:00
}
func updateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
var user models.User
//start here
user, err := GetUser(params["username"])
2021-04-18 02:03:01 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
2021-04-18 02:03:01 +08:00
return
}
var userchange models.User
// we decode our body request params
err = json.NewDecoder(r.Body).Decode(&userchange)
2021-03-26 00:17:52 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
2021-04-18 02:03:01 +08:00
return
}
2021-07-02 12:03:46 +08:00
userchange.Networks = nil
2021-03-26 00:17:52 +08:00
user, err = UpdateUser(userchange, user)
if err != nil {
2021-04-30 23:30:19 +08:00
returnErrorResponse(w, r, formatError(err, "badrequest"))
2021-03-26 00:17:52 +08:00
return
}
json.NewEncoder(w).Encode(user)
}
2021-07-02 12:03:46 +08:00
func updateUserAdm(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
var user models.User
//start here
user, err := GetUser(params["username"])
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
var userchange models.User
// we decode our body request params
err = json.NewDecoder(r.Body).Decode(&userchange)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
user, err = UpdateUser(userchange, user)
if err != nil {
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
json.NewEncoder(w).Encode(user)
}
2021-04-18 02:03:01 +08:00
func DeleteUser(user string) (bool, error) {
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
deleted := false
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
collection := mongoconn.Client.Database("netmaker").Collection("users")
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
filter := bson.M{"username": user}
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
result, err := collection.DeleteOne(ctx, filter)
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
deletecount := result.DeletedCount
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
if deletecount > 0 {
deleted = true
}
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
defer cancel()
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
return deleted, err
2021-03-26 00:17:52 +08:00
}
func deleteUser(w http.ResponseWriter, r *http.Request) {
// Set header
w.Header().Set("Content-Type", "application/json")
// get params
var params = mux.Vars(r)
success, err := DeleteUser(params["username"])
2021-04-15 10:59:25 +08:00
if err != nil {
2021-04-18 02:03:01 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
2021-03-26 00:17:52 +08:00
return
2021-04-15 10:59:25 +08:00
} else if !success {
2021-04-18 02:03:01 +08:00
returnErrorResponse(w, r, formatError(errors.New("Delete unsuccessful."), "badrequest"))
return
}
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(params["username"] + " deleted.")
}
func ValidateUser(operation string, user models.User) error {
2021-04-18 02:03:01 +08:00
v := validator.New()
err := v.Struct(user)
if err != nil {
for _, e := range err.(validator.ValidationErrors) {
fmt.Println(e)
}
}
return err
2021-03-26 00:17:52 +08:00
}