Compare commits

..

17 commits

Author SHA1 Message Date
Imbus
7db03e8dbd Merge branch 'imbs' into dev 2024-03-19 01:43:10 +01:00
Imbus
5f88e92415 Merge branch 'imbs' of git.silversoft.se:Imbus/TTime into imbs 2024-03-19 01:40:36 +01:00
borean
3125b511bb correcting AddProject 2024-03-19 01:38:40 +01:00
Imbus
09014c6659 Better test feedback in python script 2024-03-19 01:38:39 +01:00
Imbus
e498f0ed63 Silencing python testing, optional verbose output 2024-03-19 01:38:39 +01:00
Imbus
68b01f2144 Merge branch 'borean' of github.com:imbus64/TTime into borean 2024-03-19 01:23:18 +01:00
borean
58d9001be3 AddProject changed so that user is promoted to projectmanager 2024-03-19 01:23:07 +01:00
Imbus
5bcca0202b Better test feedback in python script 2024-03-19 01:12:14 +01:00
borean
0217f2b512 AddProject changed so that user is promoted to projectmanager 2024-03-19 01:10:02 +01:00
Imbus
c03be8c5d9 Path rename in python testing script 2024-03-19 00:46:28 +01:00
Imbus
b174ec8922 Rename for clarity and consistensy with TS api 2024-03-19 00:41:30 +01:00
Imbus
2cfbcd15a7 Merge branch 'docs' of github.com:imbus64/TTime into docs 2024-03-19 00:34:15 +01:00
Samuel Högbom Aronson
9ce70e74e9 tyding up and tryinng to get tokens in docs to work 2024-03-19 00:33:38 +01:00
Samuel Högbom Aronson
3e35586bbe finished docs for user reletaded stucts and added endpoint for listallusers 2024-03-19 00:33:38 +01:00
Imbus
7e4e35f597 Silencing python testing, optional verbose output 2024-03-19 00:31:15 +01:00
Samuel Högbom Aronson
8711f9a20d tyding up and tryinng to get tokens in docs to work 2024-03-19 00:27:31 +01:00
Samuel Högbom Aronson
ad85194d4f finished docs for user reletaded stucts and added endpoint for listallusers 2024-03-18 23:21:49 +01:00
5 changed files with 205 additions and 59 deletions

View file

@ -73,6 +73,11 @@ const docTemplate = `{
},
"/loginerenew": {
"post": {
"security": [
{
"bererToken": []
}
],
"description": "renews the users token",
"consumes": [
"application/json"
@ -83,7 +88,7 @@ const docTemplate = `{
"tags": [
"User"
],
"summary": "renews the users token",
"summary": "LoginRenews",
"responses": {
"200": {
"description": "Successfully signed token for user",
@ -106,6 +111,58 @@ const docTemplate = `{
}
}
},
"/promoteToAdmin": {
"post": {
"description": "promote chosen user to admin",
"consumes": [
"application/json"
],
"produces": [
"text/plain"
],
"tags": [
"User"
],
"summary": "PromoteToAdmin",
"parameters": [
{
"description": "user info",
"name": "NewUser",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/types.NewUser"
}
}
],
"responses": {
"200": {
"description": "Successfully prometed user",
"schema": {
"type": "json"
}
},
"400": {
"description": "bad request",
"schema": {
"type": "string"
}
},
"401": {
"description": "Unauthorized",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal server error",
"schema": {
"type": "string"
}
}
}
}
},
"/register": {
"post": {
"description": "Register a new user",
@ -118,7 +175,7 @@ const docTemplate = `{
"tags": [
"User"
],
"summary": "Register a new user",
"summary": "Register",
"parameters": [
{
"description": "User to register",
@ -164,7 +221,7 @@ const docTemplate = `{
"tags": [
"User"
],
"summary": "Deletes a user",
"summary": "UserDelete",
"responses": {
"200": {
"description": "User deleted",
@ -192,6 +249,41 @@ const docTemplate = `{
}
}
}
},
"/users/all": {
"get": {
"description": "lists all users",
"consumes": [
"application/json"
],
"produces": [
"text/plain"
],
"tags": [
"User"
],
"summary": "ListsAllUsers",
"responses": {
"200": {
"description": "Successfully signed token for user",
"schema": {
"type": "json"
}
},
"401": {
"description": "Unauthorized",
"schema": {
"type": "string"
}
},
"500": {
"description": "Internal server error",
"schema": {
"type": "string"
}
}
}
}
}
},
"definitions": {
@ -207,6 +299,13 @@ const docTemplate = `{
}
}
},
"securityDefinitions": {
"bererToken": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
},
"externalDocs": {
"description": "OpenAPI",
"url": "https://swagger.io/resources/open-api/"

View file

@ -201,7 +201,18 @@ func (d *Db) GetProjectId(projectname string) (int, error) {
// Creates a new project in the database, associated with a user
func (d *Db) AddProject(name string, description string, username string) error {
_, err := d.Exec(projectInsert, name, description, username)
tx := d.MustBegin()
_, err := tx.Exec(projectInsert, name, description, username)
if err != nil {
tx.Rollback()
return err
}
_, err = tx.Exec(changeUserRole, "project_manager", username, name)
if err != nil {
tx.Rollback()
return err
}
tx.Commit()
return err
}

View file

@ -12,15 +12,15 @@ import (
// Register is a simple handler that registers a new user
//
// @Summary Register a new user
// @Summary Register
// @Description Register a new user
// @Tags User
// @Accept json
// @Produce plain
// @Param NewUser body types.NewUser true "User to register"
// @Success 200 {string} string "User added"
// @Failure 400 {string} string "Bad request"
// @Failure 500 {string} string "Internal server error"
// @Param NewUser body types.NewUser true "User to register"
// @Success 200 {string} string "User added"
// @Failure 400 {string} string "Bad request"
// @Failure 500 {string} string "Internal server error"
// @Router /register [post]
func (gs *GState) Register(c *fiber.Ctx) error {
u := new(types.NewUser)
@ -42,15 +42,15 @@ func (gs *GState) Register(c *fiber.Ctx) error {
// This path should obviously be protected in the future
// UserDelete deletes a user from the database
//
// @Summary Deletes a user
// @Summary UserDelete
// @Description UserDelete deletes a user from the database
// @Tags User
// @Accept json
// @Produce plain
// @Success 200 {string} string "User deleted"
// @Failure 403 {string} string "You can only delete yourself"
// @Failure 500 {string} string "Internal server error"
// @Failure 401 {string} string "Unauthorized"
// @Success 200 {string} string "User deleted"
// @Failure 403 {string} string "You can only delete yourself"
// @Failure 500 {string} string "Internal server error"
// @Failure 401 {string} string "Unauthorized"
// @Router /userdelete/{username} [delete]
func (gs *GState) UserDelete(c *fiber.Ctx) error {
// Read from path parameters
@ -79,12 +79,12 @@ func (gs *GState) UserDelete(c *fiber.Ctx) error {
// @Description logs the user in and returns a jwt token
// @Tags User
// @Accept json
// @Param NewUser body types.NewUser true "login info"
// @Param NewUser body types.NewUser true "login info"
// @Produce plain
// @Success 200 Token types.Token "Successfully signed token for user"
// @Failure 400 {string} string "Bad request"
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal server error"
// @Success 200 Token types.Token "Successfully signed token for user"
// @Failure 400 {string} string "Bad request"
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal server error"
// @Router /login [post]
func (gs *GState) Login(c *fiber.Ctx) error {
// The body type is identical to a NewUser
@ -125,14 +125,15 @@ func (gs *GState) Login(c *fiber.Ctx) error {
// LoginRenew is a simple handler that renews the token
//
// @Summary renews the users token
// @Summary LoginRenews
// @Description renews the users token
// @Security bererToken
// @Tags User
// @Accept json
// @Produce plain
// @Success 200 Token types.Token "Successfully signed token for user"
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal server error"
// @Success 200 Token types.Token "Successfully signed token for user"
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal server error"
// @Router /loginerenew [post]
func (gs *GState) LoginRenew(c *fiber.Ctx) error {
user := c.Locals("user").(*jwt.Token)
@ -158,6 +159,16 @@ func (gs *GState) LoginRenew(c *fiber.Ctx) error {
}
// ListAllUsers is a handler that returns a list of all users in the application database
//
// @Summary ListsAllUsers
// @Description lists all users
// @Tags User
// @Accept json
// @Produce plain
// @Success 200 {json} json "Successfully signed token for user"
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal server error"
// @Router /users/all [get]
func (gs *GState) ListAllUsers(c *fiber.Ctx) error {
// Get all users from the database
users, err := gs.Db.GetAllUsersApplication()
@ -171,6 +182,17 @@ func (gs *GState) ListAllUsers(c *fiber.Ctx) error {
return c.JSON(users)
}
// @Summary PromoteToAdmin
// @Description promote chosen user to admin
// @Tags User
// @Accept json
// @Produce plain
// @Param NewUser body types.NewUser true "user info"
// @Success 200 {json} json "Successfully prometed user"
// @Failure 400 {string} string "bad request"
// @Failure 401 {string} string "Unauthorized"
// @Failure 500 {string} string "Internal server error"
// @Router /promoteToAdmin [post]
func (gs *GState) PromoteToAdmin(c *fiber.Ctx) error {
// Extract the username from the request body
var newUser types.NewUser

View file

@ -23,6 +23,10 @@ import (
// @license.name AGPL
// @license.url https://www.gnu.org/licenses/agpl-3.0.html
//@securityDefinitions.apikey bererToken
//@in header
//@name Authorization
// @host localhost:8080
// @BasePath /api
@ -79,7 +83,7 @@ func main() {
}))
// Protected routes (require a valid JWT bearer token authentication header)
server.Post("/api/submitReport", gs.SubmitWeeklyReport)
server.Post("/api/submitWeeklyReport", gs.SubmitWeeklyReport)
server.Get("/api/getUserProjects", gs.GetUserProjects)
server.Post("/api/loginrenew", gs.LoginRenew)
server.Delete("/api/userdelete/:username", gs.UserDelete) // Perhaps just use POST to avoid headaches
@ -89,7 +93,7 @@ func main() {
server.Post("/api/signReport", gs.SignReport)
server.Put("/api/addUserToProject", gs.AddUserToProjectHandler)
server.Post("/api/promoteToAdmin", gs.PromoteToAdmin)
server.Get("/api/users/all", gs.ListAllUsers)
// Announce the port we are listening on and start the server
err = server.Listen(fmt.Sprintf(":%d", conf.Port))
if err != nil {

View file

@ -2,6 +2,16 @@ import requests
import string
import random
debug_output = False
def gprint(*args, **kwargs):
print("\033[92m", *args, "\033[00m", **kwargs)
print("Running Tests...")
def dprint(*args, **kwargs):
if debug_output:
print(*args, **kwargs)
def randomString(len=10):
"""Generate a random string of fixed length"""
@ -20,7 +30,7 @@ base_url = "http://localhost:8080"
registerPath = base_url + "/api/register"
loginPath = base_url + "/api/login"
addProjectPath = base_url + "/api/project"
submitReportPath = base_url + "/api/submitReport"
submitReportPath = base_url + "/api/submitWeeklyReport"
getWeeklyReportPath = base_url + "/api/getWeeklyReport"
getProjectPath = base_url + "/api/project"
signReportPath = base_url + "/api/signReport"
@ -31,7 +41,7 @@ getUserProjectsPath = base_url + "/api/getUserProjects"
def test_get_user_projects():
print("Testing get user projects")
dprint("Testing get user projects")
loginResponse = login("user2", "123")
# Check if the user is added to the project
response = requests.get(
@ -39,29 +49,29 @@ def test_get_user_projects():
json={"username": "user2"},
headers={"Authorization": "Bearer " + loginResponse.json()["token"]},
)
print(response.text)
print(response.json())
dprint(response.text)
dprint(response.json())
assert response.status_code == 200, "Get user projects failed"
print("got user projects successfully")
gprint("test_get_user_projects successful")
# Posts the username and password to the register endpoint
def register(username: string, password: string):
print("Registering with username: ", username, " and password: ", password)
dprint("Registering with username: ", username, " and password: ", password)
response = requests.post(
registerPath, json={"username": username, "password": password}
)
print(response.text)
dprint(response.text)
return response
# Posts the username and password to the login endpoint
def login(username: string, password: string):
print("Logging in with username: ", username, " and password: ", password)
dprint("Logging in with username: ", username, " and password: ", password)
response = requests.post(
loginPath, json={"username": username, "password": password}
)
print(response.text)
dprint(response.text)
return response
@ -69,7 +79,8 @@ def login(username: string, password: string):
def test_login():
response = login(username, "always_same")
assert response.status_code == 200, "Login failed"
print("Login successful")
dprint("Login successful")
gprint("test_login successful")
return response.json()["token"]
@ -77,8 +88,7 @@ def test_login():
def test_create_user():
response = register(username, "always_same")
assert response.status_code == 200, "Registration failed"
print("Registration successful")
gprint("test_create_user successful")
# Test function to add a project
def test_add_project():
@ -89,10 +99,9 @@ def test_add_project():
json={"name": projectName, "description": "This is a project"},
headers={"Authorization": "Bearer " + token},
)
print(response.text)
dprint(response.text)
assert response.status_code == 200, "Add project failed"
print("Add project successful")
gprint("test_add_project successful")
# Test function to submit a report
def test_submit_report():
@ -111,10 +120,9 @@ def test_submit_report():
},
headers={"Authorization": "Bearer " + token},
)
print(response.text)
dprint(response.text)
assert response.status_code == 200, "Submit report failed"
print("Submit report successful")
gprint("test_submit_report successful")
# Test function to get a weekly report
def test_get_weekly_report():
@ -124,8 +132,9 @@ def test_get_weekly_report():
headers={"Authorization": "Bearer " + token},
params={"username": username, "projectName": projectName, "week": 1},
)
print(response.text)
dprint(response.text)
assert response.status_code == 200, "Get weekly report failed"
gprint("test_get_weekly_report successful")
# Tests getting a project by id
@ -135,8 +144,9 @@ def test_get_project():
getProjectPath + "/1", # Assumes that the project with id 1 exists
headers={"Authorization": "Bearer " + token},
)
print(response.text)
dprint(response.text)
assert response.status_code == 200, "Get project failed"
gprint("test_get_project successful")
# Test function to add a user to a project
@ -144,13 +154,13 @@ def test_add_user_to_project():
# Log in as a site admin
admin_username = randomString()
admin_password = "admin_password"
print(
dprint(
"Registering with username: ", admin_username, " and password: ", admin_password
)
response = requests.post(
registerPath, json={"username": admin_username, "password": admin_password}
)
print(response.text)
dprint(response.text)
admin_token = login(admin_username, admin_password).json()["token"]
response = requests.post(
@ -158,9 +168,9 @@ def test_add_user_to_project():
json={"username": admin_username},
headers={"Authorization": "Bearer " + admin_token},
)
print(response.text)
dprint(response.text)
assert response.status_code == 200, "Promote to site admin failed"
print("Admin promoted to site admin successfully")
dprint("Admin promoted to site admin successfully")
# Create a new user to add to the project
new_user = randomString()
@ -173,10 +183,9 @@ def test_add_user_to_project():
headers={"Authorization": "Bearer " + admin_token},
)
print(response.text)
dprint(response.text)
assert response.status_code == 200, "Add user to project failed"
print("Add user to project successful")
gprint("test_add_user_to_project successful")
# Test function to sign a report
def test_sign_report():
@ -187,13 +196,13 @@ def test_sign_report():
# Register an admin
admin_username = randomString()
admin_password = "admin_password2"
print(
dprint(
"Registering with username: ", admin_username, " and password: ", admin_password
)
response = requests.post(
registerPath, json={"username": admin_username, "password": admin_password}
)
print(response.text)
dprint(response.text)
# Log in as the admin
admin_token = login(admin_username, admin_password).json()["token"]
@ -213,7 +222,7 @@ def test_sign_report():
headers={"Authorization": "Bearer " + admin_token},
)
assert response.status_code == 200, "Add project manager to project failed"
print("Project manager added to project successfully")
dprint("Project manager added to project successfully")
# Log in as the project manager
project_manager_token = login(project_manager, "project_manager_password").json()[
@ -237,7 +246,7 @@ def test_sign_report():
headers={"Authorization": "Bearer " + token},
)
assert response.status_code == 200, "Submit report failed"
print("Submit report successful")
dprint("Submit report successful")
# Retrieve the report ID
response = requests.get(
@ -245,7 +254,7 @@ def test_sign_report():
headers={"Authorization": "Bearer " + token},
params={"username": username, "projectName": projectName, "week": 1},
)
print(response.text)
dprint(response.text)
report_id = response.json()["reportId"]
# Sign the report as the project manager
@ -255,7 +264,7 @@ def test_sign_report():
headers={"Authorization": "Bearer " + project_manager_token},
)
assert response.status_code == 200, "Sign report failed"
print("Sign report successful")
dprint("Sign report successful")
# Retrieve the report ID again for confirmation
response = requests.get(
@ -263,7 +272,8 @@ def test_sign_report():
headers={"Authorization": "Bearer " + token},
params={"username": username, "projectName": projectName, "week": 1},
)
print(response.text)
dprint(response.text)
gprint("test_sign_report successful")
if __name__ == "__main__":