Skip to content

Add initial user API #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified backend/cmd/server/repository/database/thunderdb.db
Binary file not shown.
16 changes: 16 additions & 0 deletions backend/dbscripts/thunderdb/postgress.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
-- Table to store Users
CREATE TABLE "USER" (
ID INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
USER_ID VARCHAR(36) UNIQUE NOT NULL,
ORG_ID VARCHAR(36) NOT NULL,
TYPE VARCHAR(50) NOT NULL,
ATTRIBUTES JSONB,
CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);

-- Table to store basic service provider (app) details.
CREATE TABLE SP_APP (
ID INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
Expand Down Expand Up @@ -102,3 +113,8 @@ VALUES
('550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440001', '550e8400-e29b-41d4-a716-446655440003'),
('550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440001', '550e8400-e29b-41d4-a716-446655440004'),
('550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440002', '550e8400-e29b-41d4-a716-446655440005');

INSERT INTO "USER" (USER_ID, ORG_ID, TYPE, ATTRIBUTES)
VALUES
('550e8400-e29b-41d4-a716-446655440000', '456e8400-e29b-41d4-a716-446655440001', 'person',
'{"age": 30, "roles": ["admin", "user"], "address": {"city": "Colombo", "zip": "00100"}}');
18 changes: 18 additions & 0 deletions backend/dbscripts/thunderdb/sqlite.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
-- Table to store Users
CREATE TABLE USER (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
USER_ID VARCHAR(36) UNIQUE NOT NULL,
ORG_ID VARCHAR(36) NOT NULL,
TYPE TEXT NOT NULL,
ATTRIBUTES TEXT,
CREATED_AT TEXT DEFAULT (datetime('now')),
UPDATED_AT TEXT DEFAULT (datetime('now'))
);

-- Table to store basic service provider (app) details.
CREATE TABLE SP_APP (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
Expand Down Expand Up @@ -102,3 +113,10 @@ VALUES
('550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440001', '550e8400-e29b-41d4-a716-446655440003'),
('550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440001', '550e8400-e29b-41d4-a716-446655440004'),
('550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440002', '550e8400-e29b-41d4-a716-446655440005');

INSERT INTO USER (USER_ID, ORG_ID, TYPE, ATTRIBUTES, CREATED_AT, UPDATED_AT)
VALUES (
'550e8400-e29b-41d4-a716-446655440000', '456e8400-e29b-41d4-a716-446655440001', 'person',
'{"age": 30, "roles": ["admin", "user"], "address": {"city": "Colombo", "zip": "00100"}}',
datetime('now'), datetime('now')
);
3 changes: 3 additions & 0 deletions backend/internal/system/managers/servicemanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ func (sm *ServiceManager) RegisterServices() error {

// Register the token service.
services.NewTokenService(sm.mux)

// Register the User service.
services.NewUserService(sm.mux)
// Register the Application service.
services.NewApplicationService(sm.mux)

Expand Down
47 changes: 47 additions & 0 deletions backend/internal/system/services/userservice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2025, WSO2 LLC. (http://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package services

import (
"github.com/asgardeo/thunder/internal/user/handler"
"net/http"
)

type UserService struct {
userHandler *handler.UserHandler
}

func NewUserService(mux *http.ServeMux) *UserService {

instance := &UserService{
userHandler: handler.NewUserHandler(),
}
instance.RegisterRoutes(mux)

return instance
}

func (s *UserService) RegisterRoutes(mux *http.ServeMux) {

mux.HandleFunc("POST /users", s.userHandler.HandleUserPostRequest)
mux.HandleFunc("GET /users", s.userHandler.HandleUserListRequest)
mux.HandleFunc("GET /users/", s.userHandler.HandleUserGetRequest)
mux.HandleFunc("PUT /users/", s.userHandler.HandleUserPutRequest)
mux.HandleFunc("DELETE /users/", s.userHandler.HandleUserDeleteRequest)
}
258 changes: 258 additions & 0 deletions backend/internal/user/handler/userhandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
/*
* Copyright (c) 2025, WSO2 LLC. (http://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package handler

import (
"encoding/json"
"github.com/asgardeo/thunder/internal/system/log"
"github.com/asgardeo/thunder/internal/user/model"
userprovider "github.com/asgardeo/thunder/internal/user/provider"
"net/http"
"strings"
"sync"
)

// @title User Management API
// @version 1.0
// @description This API is used to manage users.
//
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
//
// @host localhost:8090
// @BasePath /
type UserHandler struct {
store map[string]model.User
mu *sync.RWMutex
}

func NewUserHandler() *UserHandler {

return &UserHandler{
store: make(map[string]model.User),
mu: &sync.RWMutex{},
}
}

// HandleUserPostRequest handles the user request.
//
// @Summary Create an user
// @Description Creates a new user with the provided details.
// @Tags users
// @Accept json
// @Produce json
// @Param user body model.User true "User data"
// @Success 201 {object} model.User
// @Failure 400 {string} "Bad Request: The request body is malformed or contains invalid data."
// @Failure 500 {string} "Internal Server Error: An unexpected error occurred while processing the request."
// @Router /users [post]
func (ah *UserHandler) HandleUserPostRequest(w http.ResponseWriter, r *http.Request) {

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed during last week's review, shall we remove empty line after the func definition?

logger := log.GetLogger().With(log.String(log.LOGGER_KEY_COMPONENT_NAME, "UserHandler"))

var userInCreationRequest model.User
if err := json.NewDecoder(r.Body).Decode(&userInCreationRequest); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}

// Create the user using the user service.
userProvider := userprovider.NewUserProvider()
userService := userProvider.GetUserService()
createdUser, err := userService.CreateUser(&userInCreationRequest)
if err != nil {
http.Error(w, "Failed to create user", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)

err = json.NewEncoder(w).Encode(createdUser)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}

// Log the user creation response.
logger.Debug("User POST response sent", log.String("user id", createdUser.Id))
}

// HandleUserListRequest handles the user request.
//
// @Summary List users
// @Description Retrieve a list of all users.
// @Tags users
// @Accept json
// @Produce json
// @Success 200 {array} model.User
// @Failure 400 {string} "Bad Request: The request body is malformed or contains invalid data."
// @Failure 500 {string} "Internal Server Error: An unexpected error occurred while processing the request."
// @Router /users [get]
func (ah *UserHandler) HandleUserListRequest(w http.ResponseWriter, r *http.Request) {

logger := log.GetLogger().With(log.String(log.LOGGER_KEY_COMPONENT_NAME, "UserHandler"))

// Get the user list using the user service.
userProvider := userprovider.NewUserProvider()
userService := userProvider.GetUserService()
users, err := userService.GetUserList()
if err != nil {
http.Error(w, "Failed get user list", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(users)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}

// Log the user response.
logger.Debug("User GET (list) response sent")
}

// HandleUserGetRequest handles the user request.
//
// @Summary Get an user by ID
// @Description Retrieve a specific user using its ID.
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "User ID"
// @Success 200 {object} model.User
// @Failure 400 {string} "Bad Request: The request body is malformed or contains invalid data."
// @Failure 404 {string} "Not Found: The user with the specified ID does not exist."
// @Failure 500 {string} "Internal Server Error: An unexpected error occurred while processing the request."
// @Router /users/{id} [get]
func (ah *UserHandler) HandleUserGetRequest(w http.ResponseWriter, r *http.Request) {

logger := log.GetLogger().With(log.String(log.LOGGER_KEY_COMPONENT_NAME, "UserHandler"))

id := strings.TrimPrefix(r.URL.Path, "/users/")
if id == "" {
http.Error(w, "Missing user id", http.StatusBadRequest)
return
}

// Get the user using the user service.
userProvider := userprovider.NewUserProvider()
userService := userProvider.GetUserService()
user, err := userService.GetUser(id)
if err != nil {
http.Error(w, "Failed get user", http.StatusInternalServerError)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should handle client errors here right? Otherwise there will be a 500 for non existing users as well.
Same with put and delete

return
}

w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(user)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}

// Log the user response.
logger.Debug("User GET response sent", log.String("user id", id))
}

// HandleUserPutRequest handles the user request.
//
// @Summary Update an user
// @Description Update the details of an existing user.
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "User ID"
// @Param user body model.User true "Updated user data"
// @Success 200 {object} model.User
// @Failure 400 {string} "Bad Request: The request body is malformed or contains invalid data."
// @Failure 404 {string} "Not Found: The user with the specified ID does not exist."
// @Failure 500 {string} "Internal Server Error: An unexpected error occurred while processing the request."
// @Router /users/{id} [put]
func (ah *UserHandler) HandleUserPutRequest(w http.ResponseWriter, r *http.Request) {

logger := log.GetLogger().With(log.String(log.LOGGER_KEY_COMPONENT_NAME, "UserHandler"))

id := strings.TrimPrefix(r.URL.Path, "/users/")
if id == "" {
http.Error(w, "Missing user id", http.StatusBadRequest)
return
}

var updatedUser model.User
if err := json.NewDecoder(r.Body).Decode(&updatedUser); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
updatedUser.Id = id

// Update the user using the user service.
userProvider := userprovider.NewUserProvider()
userService := userProvider.GetUserService()
user, err := userService.UpdateUser(id, &updatedUser)
if err != nil {
http.Error(w, "Failed get user", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)

// Log the user response.
logger.Debug("User PUT response sent", log.String("user id", id))
}

// HandleUserDeleteRequest handles the user request.
//
// @Summary Delete an user
// @Description Delete an user using its ID.
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "User ID"
// @Success 204
// @Failure 400 {string} "Bad Request: The request body is malformed or contains invalid data."
// @Failure 404 {string} "Not Found: The user with the specified ID does not exist."
// @Failure 500 {string} "Internal Server Error: An unexpected error occurred while processing the request."
// @Router /users/{id} [delete]
func (ah *UserHandler) HandleUserDeleteRequest(w http.ResponseWriter, r *http.Request) {

logger := log.GetLogger().With(log.String(log.LOGGER_KEY_COMPONENT_NAME, "UserHandler"))

id := strings.TrimPrefix(r.URL.Path, "/users/")
if id == "" {
http.Error(w, "Missing user id", http.StatusBadRequest)
return
}

// Delete the user using the user service.
userProvider := userprovider.NewUserProvider()
userService := userProvider.GetUserService()
err := userService.DeleteUser(id)
if err != nil {
http.Error(w, "Failed delete user", http.StatusInternalServerError)
return
}

w.WriteHeader(http.StatusNoContent)

// Log the user response.
logger.Debug("User DELETE response sent", log.String("user id", id))
}
28 changes: 28 additions & 0 deletions backend/internal/user/model/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2025, WSO2 LLC. (http://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package model

import "encoding/json"

type User struct {
Id string `json:"id,omitempty"`
OrgId string `json:"org_id,omitempty"`
Type string `json:"type,omitempty"`
Attributes json.RawMessage `json:"attributes,omitempty"`
}
Loading
Loading