diff --git a/.env b/.env index 1f5f0f141e9c1391bcd5b0325fbb516f0fa4bbfb..992d1332de568160529eb77e58ab3ab53405b083 100644 --- a/.env +++ b/.env @@ -3,8 +3,4 @@ LISTEN_ADDR=0.0.0.0 PORT=8080 LOGTAIL_TOKEN= HTTP_TIMEOUT_SEC=2 -LOG_FLUSH_INTERVAL_MS=1000 -DB_STRING="host=localhost user=ocw password=ocw dbname=ocw-db port=5433 sslmode=disable TimeZone=Asia/Shanghai" -SMTP_USERNAME="noreply@ocw.id" -SMTP_SERVER=localhost -SMTP_PORT=1025 \ No newline at end of file +LOG_FLUSH_INTERVAL_MS=1000 \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index afb1b518807dedc2f9b7e1f399cc585878bcee32..0000000000000000000000000000000000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Launch Package", - "type": "go", - "request": "launch", - "mode": "auto", - "program": "${workspaceFolder}" - } - ] -} diff --git a/README.md b/README.md index a22908f3646bda0e98b61c433a6d598de9f47a90..09750369fb1b69c3a5ec6e7555749c8c3036a6bb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# ITBOpenCourseWare Backend +# OCW Backend Repository ini adalah repository untuk OCW Backend @@ -11,10 +11,9 @@ Ini adalah requirement untuk menjalankan template ini: 3. Postgresql (Optional, when using docker) 4. GNU Make 4.3 (Optional, when using docker) 5. Minio (Optional, when using docker) -6. Google wire v0.5.0 (<https://github.com/google/wire>) [MANDATORY] -7. swaggo (<https://github.com/swaggo/swag>) -8. Air command line (<https://github.com/cosmtrek/air>) -9. Redis +6. Google wire v0.5.0 (https://github.com/google/wire) [MANDATORY] +7. Air command line (https://github.com/cosmtrek/air) +8. Redis ## Cara menjalankan @@ -23,66 +22,3 @@ Untuk menjalankan server ini, gunakan: ```sh make watch ``` - -## Development Guide - -1. Checkout ke branch staging + pull - - ```sh - git checkout staging - git pull - ``` - -2. Buat branch baru dari staging dengan format `feat/s<nomor sprint>-sb<nomor sb>-<nama fitur dipisah dengan strip (-)>`. Jika membuat perubahan dari fitur yang sudah ada di staging, formatnya menjadi `fix/s<nomor sprint>-sb<nomor sb>-<apa yang diubah dari fitur tersebut>` - - ```sh - git checkout -b feat/s1-sb1-login - ``` - -3. Lakukan perubahan pada branch tersebut, commit dengan format `feat(<scope fitur>): <isi perubahan>`. Jika melakukan perubahan pada fitur yang sudah ada, formatnya menjadi `fix(<scope fitur>): <isi perubahan>`, lain-lainnya bisa dilihat di [semantic commit](https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716) - - ```sh - git commit -m "feat(login): add login page" - ``` - -4. Push branch ke remote - - ```sh - git push origin feat/s1-sb1-login - ``` - -5. Buat merge request ke branch staging, tambah assignee diri sendiri dan reviewer - -### Handling Accidents - -- Salah branch untuk commit? - - Gunakan `git reset --soft HEAD~1` untuk menghapus commit terakhir, lalu `git checkout <branch yang benar>` untuk kembali ke branch yang benar. Commit ulang dengan format yang benar. Tapi hal ini hanya bisa dilakukan sebelum push ke remote. - - Baru sadar salah branch setelah beberapa commit? Gunakan `git reset --soft HEAD~<jumlah commit sebelumnya>` - -- Ada update baru dari staging ketika sedang mengerjakan pekerjaan di branch sendiri? - - Sebenarnya jika itu pekerjaan orang yang tidak ada hubungannya dengan anda, tidak masalah. - - Tapi jika iya, contohnya ingin mengambil komponen yang baru ada di staging, gunakan `git rebase staging` untuk mengambil update dari staging. Jika ada konflik, selesaikan konflik tersebut, lalu `git add .` dan `git rebase --continue` untuk melanjutkan rebase. Jika sudah selesai, push ulang branch anda ke remote dengan `git push -f`. - - Sistem kerja rebase *basically* memutuskan semua commit pekerjaan anda sampai commit terakhir yang sinkron dengan staging, git pull dari staging, lalu menyambungkan kembali sehingga dapat meminimalisir konflik, walaupun tetap bisa ada konflik, terutama jika ada perubahan di file sama. Selengkapnya bisa dilihat ilustrasinya sebagai berikut. - -  - -- Ada konflik saat melakukan rebase? - - Selesaikan konflik tersebut, lalu `git add .` dan `git rebase --continue` untuk melanjutkan rebase. Jika sudah selesai, push ulang branch anda ke remote dengan `git push -f`. - -- Ada konflik saat melakukan merge request? - - Selesaikan konflik tersebut, lalu `git add .` dan `git commit --amend` untuk menggabungkan konflik tersebut ke commit terakhir (jika malas). Push ulang branch anda ke remote dengan `git push -f`. - -- Ada salah di pesan commit terakhir? - - Gunakan `git commit --amend` untuk mengganti commit terakhir dengan commit baru. Jika sudah selesai, push ulang branch anda ke remote dengan `git push -f`. - -- Baru sadar ada salah pesan di beberapa commit sebelumnya? - - Gunakan `git rebase -i HEAD~<jumlah commit sebelumnya>` untuk mengubah pesan commit dari commit terakhir hingga beberapa sebelumnya. Jika sudah selesai, push ulang branch anda ke remote dengan `git push -f`. diff --git a/di.go b/di.go index 66bbf655c71fb48a23bc81ddca3513bcfec22cc9..25590b935772d6f66e014cea15c7885f889eb4fd 100644 --- a/di.go +++ b/di.go @@ -8,8 +8,6 @@ import ( "gitlab.informatika.org/ocw/ocw-backend/handler" "gitlab.informatika.org/ocw/ocw-backend/middleware" - "gitlab.informatika.org/ocw/ocw-backend/provider" - "gitlab.informatika.org/ocw/ocw-backend/repository" "gitlab.informatika.org/ocw/ocw-backend/routes" "gitlab.informatika.org/ocw/ocw-backend/service" "gitlab.informatika.org/ocw/ocw-backend/utils" @@ -20,12 +18,10 @@ import ( func CreateServer() (app.Server, error) { wire.Build( utils.UtilSet, - repository.RepositorySet, handler.HandlerSet, middleware.MiddlewareSet, routes.RoutesSet, service.ServiceSet, - provider.ProviderSet, ) return nil, nil diff --git a/docs/docs.go b/docs/docs.go index 90d0363f2854b663778cdd7df051648418a59c2c..a98b111dc8da9f556c81a35f860f70b8bf847d49 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -61,7 +61,7 @@ const docTemplate = `{ ], "responses": { "200": { - "description": "Login Success", + "description": "OK", "schema": { "allOf": [ { @@ -78,47 +78,8 @@ const docTemplate = `{ ] } }, - "400": { - "description": "Bad Input", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.BaseResponse" - }, - { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - ] - } - }, "403": { - "description": "Login Credential Error", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "415": { - "description": "Not a json request", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "422": { - "description": "Invalid JSON input", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "500": { - "description": "Unknown Internal Error", + "description": "Forbidden", "schema": { "$ref": "#/definitions/web.BaseResponse" } @@ -167,66 +128,8 @@ const docTemplate = `{ ] } }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - } - } - } - }, - "/auth/register": { - "post": { - "description": "Generate New Account as Member", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "Register New Account", - "parameters": [ - { - "description": "Register Payload", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/register.RegisterRequestPayload" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "500": { - "description": "Internal Server Error", + "403": { + "description": "Forbidden", "schema": { "$ref": "#/definitions/web.BaseResponse" } @@ -280,38 +183,6 @@ const docTemplate = `{ } } }, - "register.RegisterRequestPayload": { - "description": "Information that should be available when do a registration process", - "type": "object", - "required": [ - "email", - "name", - "password", - "password_validation" - ], - "properties": { - "email": { - "description": "User Email", - "type": "string", - "example": "someone@example.com" - }, - "name": { - "description": "User name", - "type": "string", - "example": "someone" - }, - "password": { - "description": "User Password", - "type": "string", - "example": "secret" - }, - "password_validation": { - "description": "User Password Validation, must be same as user", - "type": "string", - "example": "secret" - } - } - }, "web.BaseResponse": { "type": "object", "properties": { diff --git a/docs/swagger.json b/docs/swagger.json index dc9d78a343021dfa865bb7bc624edde2ff07b313..442fa43a8941e6e2ba171b1a31a3da9bd35cfd73 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -53,7 +53,7 @@ ], "responses": { "200": { - "description": "Login Success", + "description": "OK", "schema": { "allOf": [ { @@ -70,47 +70,8 @@ ] } }, - "400": { - "description": "Bad Input", - "schema": { - "allOf": [ - { - "$ref": "#/definitions/web.BaseResponse" - }, - { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - ] - } - }, "403": { - "description": "Login Credential Error", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "415": { - "description": "Not a json request", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "422": { - "description": "Invalid JSON input", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "500": { - "description": "Unknown Internal Error", + "description": "Forbidden", "schema": { "$ref": "#/definitions/web.BaseResponse" } @@ -159,66 +120,8 @@ ] } }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "401": { - "description": "Unauthorized", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - } - } - } - }, - "/auth/register": { - "post": { - "description": "Generate New Account as Member", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "Register New Account", - "parameters": [ - { - "description": "Register Payload", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/register.RegisterRequestPayload" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/web.BaseResponse" - } - }, - "500": { - "description": "Internal Server Error", + "403": { + "description": "Forbidden", "schema": { "$ref": "#/definitions/web.BaseResponse" } @@ -272,38 +175,6 @@ } } }, - "register.RegisterRequestPayload": { - "description": "Information that should be available when do a registration process", - "type": "object", - "required": [ - "email", - "name", - "password", - "password_validation" - ], - "properties": { - "email": { - "description": "User Email", - "type": "string", - "example": "someone@example.com" - }, - "name": { - "description": "User name", - "type": "string", - "example": "someone" - }, - "password": { - "description": "User Password", - "type": "string", - "example": "secret" - }, - "password_validation": { - "description": "User Password Validation, must be same as user", - "type": "string", - "example": "secret" - } - } - }, "web.BaseResponse": { "type": "object", "properties": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 9c74543416b9ad2d2cb3b32c1ad3cfc340f575e9..f21c3156cb87cc9dfa4db1b7077bec04d0cc4c99 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -31,31 +31,6 @@ definitions: description: Token that used to access the resources type: string type: object - register.RegisterRequestPayload: - description: Information that should be available when do a registration process - properties: - email: - description: User Email - example: someone@example.com - type: string - name: - description: User name - example: someone - type: string - password: - description: User Password - example: secret - type: string - password_validation: - description: User Password Validation, must be same as user - example: secret - type: string - required: - - email - - name - - password - - password_validation - type: object web.BaseResponse: properties: data: {} @@ -102,7 +77,7 @@ paths: - application/json responses: "200": - description: Login Success + description: OK schema: allOf: - $ref: '#/definitions/web.BaseResponse' @@ -110,31 +85,8 @@ paths: data: $ref: '#/definitions/login.LoginResponsePayload' type: object - "400": - description: Bad Input - schema: - allOf: - - $ref: '#/definitions/web.BaseResponse' - - properties: - data: - items: - type: string - type: array - type: object "403": - description: Login Credential Error - schema: - $ref: '#/definitions/web.BaseResponse' - "415": - description: Not a json request - schema: - $ref: '#/definitions/web.BaseResponse' - "422": - description: Invalid JSON input - schema: - $ref: '#/definitions/web.BaseResponse' - "500": - description: Unknown Internal Error + description: Forbidden schema: $ref: '#/definitions/web.BaseResponse' summary: Login @@ -163,49 +115,11 @@ paths: data: $ref: '#/definitions/refresh.RefreshResponsePayload' type: object - "400": - description: Bad Request - schema: - $ref: '#/definitions/web.BaseResponse' - "401": - description: Unauthorized - schema: - $ref: '#/definitions/web.BaseResponse' - "500": - description: Internal Server Error + "403": + description: Forbidden schema: $ref: '#/definitions/web.BaseResponse' summary: Refresh Token tags: - auth - /auth/register: - post: - consumes: - - application/json - description: Generate New Account as Member - parameters: - - description: Register Payload - in: body - name: data - required: true - schema: - $ref: '#/definitions/register.RegisterRequestPayload' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/web.BaseResponse' - "400": - description: Bad Request - schema: - $ref: '#/definitions/web.BaseResponse' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/web.BaseResponse' - summary: Register New Account - tags: - - auth swagger: "2.0" diff --git a/go.mod b/go.mod index b69d320688f3db0c6bbdcc1ad19eea994fde74ea..e4ec072ee7ce0bf1e440935c9cf64e66a807fb97 100644 --- a/go.mod +++ b/go.mod @@ -6,17 +6,12 @@ require ( github.com/caarlos0/env/v6 v6.10.1 github.com/go-chi/chi/v5 v5.0.8 github.com/go-chi/cors v1.2.1 - github.com/go-playground/validator/v10 v10.11.2 - github.com/golang-jwt/jwt/v4 v4.4.3 github.com/google/wire v0.5.0 github.com/joho/godotenv v1.5.0 github.com/sirupsen/logrus v1.9.0 github.com/stretchr/testify v1.8.1 github.com/swaggo/http-swagger v1.3.3 github.com/swaggo/swag v1.8.10 - golang.org/x/crypto v0.6.0 - gorm.io/driver/postgres v1.4.6 - gorm.io/gorm v1.24.5 ) require ( @@ -24,17 +19,15 @@ require ( github.com/KyleBanks/depth v1.2.1 // indirect github.com/PuerkitoBio/purell v1.1.1 // indirect github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect - github.com/cosmtrek/air v1.41.0 // indirect - github.com/creack/pty v1.1.18 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/fatih/color v1.14.1 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/spec v0.20.8 // indirect github.com/go-openapi/swag v0.22.3 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.11.2 // indirect + github.com/golang-jwt/jwt/v4 v4.4.3 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgx/v5 v5.2.0 // indirect @@ -43,16 +36,16 @@ require ( github.com/josharian/intern v1.0.0 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/mailru/easyjson v0.7.7 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.17 // indirect - github.com/pelletier/go-toml v1.9.5 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/stretchr/objx v0.5.0 // indirect github.com/swaggo/files v1.0.0 // indirect + golang.org/x/crypto v0.6.0 // indirect golang.org/x/net v0.6.0 // indirect golang.org/x/sys v0.5.0 // indirect golang.org/x/text v0.7.0 // indirect golang.org/x/tools v0.5.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect + gorm.io/driver/postgres v1.4.6 // indirect + gorm.io/gorm v1.24.5 // indirect ) diff --git a/go.sum b/go.sum index d771a874f694fecc968e13f8658ba7de1cd1ca6f..db1952c412bd4a9347d5c577dbd6e51d28ee171c 100644 --- a/go.sum +++ b/go.sum @@ -8,18 +8,10 @@ github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/caarlos0/env/v6 v6.10.1 h1:t1mPSxNpei6M5yAeu1qtRdPAK29Nbcf/n3G7x+b3/II= github.com/caarlos0/env/v6 v6.10.1/go.mod h1:hvp/ryKXKipEkcuYjs9mI4bBCg+UI0Yhgm5Zu0ddvwc= -github.com/cosmtrek/air v1.41.0 h1:6ck2LbcVvby6cyuwE8ruia41U2nppMZGWOpq+E/EhoU= -github.com/cosmtrek/air v1.41.0/go.mod h1:+RBGjJt7T2f3I7td8Tvk0XsH/hZ3E1QBLfiWObICO4c= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= -github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w= -github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0= github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4= @@ -55,8 +47,6 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= github.com/google/wire v0.5.0 h1:I7ELFeVBr3yfPIcc8+MWvrjk+3VjbcSzoXm3JVa+jD8= github.com/google/wire v0.5.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1EoU= -github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= -github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= @@ -90,14 +80,7 @@ github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= -github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= -github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= @@ -157,8 +140,6 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= @@ -199,7 +180,6 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gorm.io/driver/postgres v1.4.6 h1:1FPESNXqIKG5JmraaH2bfCVlMQ7paLoCreFxDtqzwdc= diff --git a/handler/auth/handler.go b/handler/auth/handler.go index adae847f2baec21f127940794b447cffdb9824b3..6a8f65ba49157b46c2ddde121c86c823a8966bb2 100644 --- a/handler/auth/handler.go +++ b/handler/auth/handler.go @@ -2,7 +2,6 @@ package auth import ( "gitlab.informatika.org/ocw/ocw-backend/service/auth" - "gitlab.informatika.org/ocw/ocw-backend/service/logger" "gitlab.informatika.org/ocw/ocw-backend/utils/httputil" "gitlab.informatika.org/ocw/ocw-backend/utils/wrapper" ) @@ -11,5 +10,4 @@ type AuthHandlerImpl struct { auth.AuthService httputil.HttpUtil wrapper.WrapperUtil - logger.Logger } diff --git a/handler/auth/login.go b/handler/auth/login.go index 3ab6f0759cde01fa545c1299fb1d2f9b056afafa..ee729647365b4e536d7c3fbcf9ae2f79fb7ddcd8 100644 --- a/handler/auth/login.go +++ b/handler/auth/login.go @@ -1,11 +1,9 @@ package auth import ( - "fmt" "net/http" "github.com/go-playground/validator/v10" - "gitlab.informatika.org/ocw/ocw-backend/model/web" "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/login" ) @@ -17,26 +15,16 @@ import ( // @Produce json // @Accept json // @Param data body login.LoginRequestPayload true "Login payload" -// @Success 200 {object} web.BaseResponse{data=login.LoginResponsePayload} "Login Success" -// @Failure 400 {object} web.BaseResponse{data=[]string} "Bad Input" -// @Failure 403 {object} web.BaseResponse "Login Credential Error" -// @Failure 415 {object} web.BaseResponse "Not a json request" -// @Failure 422 {object} web.BaseResponse "Invalid JSON input" -// @Failure 500 {object} web.BaseResponse "Unknown Internal Error" +// @Success 200 {object} web.BaseResponse{data=login.LoginResponsePayload} +// @Failure 403 {object} web.BaseResponse // @Router /auth/login [post] func (a AuthHandlerImpl) Login(w http.ResponseWriter, r *http.Request) { payload := login.LoginRequestPayload{} validate := validator.New() - if r.Header.Get("Content-Type") != "application/json" { - payload := a.WrapperUtil.ErrorResponseWrap("this service only receive json input", nil) - a.HttpUtil.WriteJson(w, http.StatusUnsupportedMediaType, payload) - return - } - if err := a.HttpUtil.ParseJson(r, &payload); err != nil { - payload := a.WrapperUtil.ErrorResponseWrap("invalid json input", err.Error()) - a.HttpUtil.WriteJson(w, http.StatusUnprocessableEntity, payload) + payload := a.WrapperUtil.ErrorResponseWrap(err.Error(), nil) + a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) return } @@ -47,8 +35,12 @@ func (a AuthHandlerImpl) Login(w http.ResponseWriter, r *http.Request) { return } - errPayload := web.NewResponseErrorFromValidator(err.(validator.ValidationErrors)) - payload := a.WrapperUtil.ErrorResponseWrap(errPayload.Error(), errPayload) + errList := []string{} + for _, err := range err.(validator.ValidationErrors) { + errList = append(errList, err.Error()) + } + + payload := a.WrapperUtil.ErrorResponseWrap("input validation error", errList) a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) return } @@ -56,22 +48,8 @@ func (a AuthHandlerImpl) Login(w http.ResponseWriter, r *http.Request) { response, err := a.AuthService.Login(payload) if err != nil { - respErr, ok := err.(web.ResponseError) - if ok { - payload := a.WrapperUtil.ErrorResponseWrap(respErr.Error(), respErr) - - if respErr.Code != web.InvalidLogin { - a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) - } else { - a.HttpUtil.WriteJson(w, http.StatusForbidden, payload) - } - } else { - a.Logger.Error( - fmt.Sprintf("[AUTH] some error happened when do login: %s", err.Error()), - ) - payload := a.WrapperUtil.ErrorResponseWrap("internal server error", nil) - a.HttpUtil.WriteJson(w, http.StatusInternalServerError, payload) - } + payload := a.WrapperUtil.ErrorResponseWrap(err.Error(), nil) + a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) return } diff --git a/handler/auth/refresh.go b/handler/auth/refresh.go index 20eaed5d8803d078beed923cf0855b9bc394f438..bf8fda26d51162c13917bc13b1e02040532e3bb5 100644 --- a/handler/auth/refresh.go +++ b/handler/auth/refresh.go @@ -1,11 +1,9 @@ package auth import ( - "fmt" "net/http" "strings" - "gitlab.informatika.org/ocw/ocw-backend/model/web" "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/refresh" ) @@ -18,9 +16,7 @@ import ( // @Accept json // @Param Authorization header string true "Refresh token" // @Success 200 {object} web.BaseResponse{data=refresh.RefreshResponsePayload} -// @Failure 400 {object} web.BaseResponse -// @Failure 401 {object} web.BaseResponse -// @Failure 500 {object} web.BaseResponse +// @Failure 403 {object} web.BaseResponse // @Router /auth/refresh [post] func (a AuthHandlerImpl) Refresh(w http.ResponseWriter, r *http.Request) { payload := refresh.RefreshRequestPayload{} @@ -51,17 +47,8 @@ func (a AuthHandlerImpl) Refresh(w http.ResponseWriter, r *http.Request) { response, err := a.AuthService.Refresh(payload) if err != nil { - if errData, ok := err.(web.ResponseError); ok { - payload := a.WrapperUtil.ErrorResponseWrap(errData.Error(), errData) - a.HttpUtil.WriteJson(w, http.StatusUnauthorized, payload) - return - } - - a.Logger.Error( - fmt.Sprintf("[AUTH] some error happened when do refresh: %s", err.Error()), - ) - payload := a.WrapperUtil.ErrorResponseWrap("internal server error", nil) - a.HttpUtil.WriteJson(w, http.StatusInternalServerError, payload) + payload := a.WrapperUtil.ErrorResponseWrap(err.Error(), nil) + a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) return } diff --git a/handler/auth/register.go b/handler/auth/register.go deleted file mode 100644 index 8a24f5da071967f00ddcea7e973bd6a46230fa1b..0000000000000000000000000000000000000000 --- a/handler/auth/register.go +++ /dev/null @@ -1,77 +0,0 @@ -package auth - -import ( - "fmt" - "net/http" - "strings" - - "github.com/go-playground/validator/v10" - "gitlab.informatika.org/ocw/ocw-backend/model/web" - "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/register" -) - -// Index godoc -// -// @Tags auth -// @Summary Register New Account -// @Description Generate New Account as Member -// @Produce json -// @Accept json -// @Param data body register.RegisterRequestPayload true "Register Payload" -// @Success 200 {object} web.BaseResponse -// @Failure 400 {object} web.BaseResponse -// @Failure 500 {object} web.BaseResponse -// @Router /auth/register [post] -func (a AuthHandlerImpl) Register(w http.ResponseWriter, r *http.Request) { - payload := register.RegisterRequestPayload{} - validate := validator.New() - - if r.Header.Get("Content-Type") != "application/json" { - payload := a.WrapperUtil.ErrorResponseWrap("this service only receive json input", nil) - a.HttpUtil.WriteJson(w, http.StatusUnsupportedMediaType, payload) - return - } - - if err := a.HttpUtil.ParseJson(r, &payload); err != nil { - payload := a.WrapperUtil.ErrorResponseWrap("invalid json input", err.Error()) - a.HttpUtil.WriteJson(w, http.StatusUnprocessableEntity, payload) - return - } - - if err := validate.Struct(payload); err != nil { - if _, ok := err.(*validator.InvalidValidationError); ok { - payload := a.WrapperUtil.ErrorResponseWrap(err.Error(), nil) - a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) - return - } - - errPayload := web.NewResponseErrorFromValidator(err.(validator.ValidationErrors)) - payload := a.WrapperUtil.ErrorResponseWrap(errPayload.Error(), errPayload) - a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) - return - } - - err := a.AuthService.Register(payload) - - if err != nil { - if strings.Contains(err.Error(), "duplicate key") { - err = web.NewResponseErrorFromError(err, web.EmailExist) - } - - respErr, ok := err.(web.ResponseError) - if ok { - payload := a.WrapperUtil.ErrorResponseWrap("email was registered by other account", respErr) - a.HttpUtil.WriteJson(w, http.StatusBadRequest, payload) - } else { - a.Logger.Error( - fmt.Sprintf("[AUTH] some error happened when do register: %s", err.Error()), - ) - payload := a.WrapperUtil.ErrorResponseWrap("internal server error", nil) - a.HttpUtil.WriteJson(w, http.StatusInternalServerError, payload) - } - return - } - - responsePayload := a.WrapperUtil.SuccessResponseWrap(nil) - a.HttpUtil.WriteSuccessJson(w, responsePayload) -} diff --git a/handler/auth/types.go b/handler/auth/types.go index 71b4d1eba14c50a290f9c43565da1dd707e73f29..49aa52cee884d6fbdfb60b30b19556e1b5e18962 100644 --- a/handler/auth/types.go +++ b/handler/auth/types.go @@ -4,6 +4,5 @@ import "net/http" type AuthHandler interface { Login(w http.ResponseWriter, r *http.Request) - Register(w http.ResponseWriter, r *http.Request) Refresh(w http.ResponseWriter, r *http.Request) } diff --git a/model/domain/user/role.go b/model/domain/user/role.go index 0b036ee36a86133115151235f152272f8fe2be91..25e8bd6bb3b4c3bfc94085a2b54b85a86bab57e1 100644 --- a/model/domain/user/role.go +++ b/model/domain/user/role.go @@ -11,18 +11,18 @@ type UserRole int const ( Admin UserRole = iota - Student + Member Contributor ) var roleMapping = map[UserRole]string{ Admin: "admin", - Student: "student", + Member: "member", Contributor: "contributor", } func (ur *UserRole) Scan(value interface{}) error { - val := value.(string) + val := string(value.([]byte)) for key, label := range roleMapping { if label == val { diff --git a/model/domain/user/user.go b/model/domain/user/user.go index f2fbb565f6dd4aa94cbf7f15b260980ead0351f9..62d5e1ec20457e1f4cecf43269ca308beb5913de 100644 --- a/model/domain/user/user.go +++ b/model/domain/user/user.go @@ -1,17 +1,11 @@ package user -import "time" - type User struct { Email string `gorm:"primaryKey"` Password string Name string Role UserRole `gorm:"type:user_role"` IsActivated bool - CreatedAt time.Time - UpdatedAt time.Time -} - -func (User) TableName() string { - return "user" + CreatedAt int64 `gorm:"autoCreateTime:nano"` + UpdatedAt int64 `gorm:"autoUpdateTime:nano"` } diff --git a/model/web/auth/register/request.go b/model/web/auth/register/request.go deleted file mode 100644 index 48d58105956364d445c27ea82129f2d0c27581eb..0000000000000000000000000000000000000000 --- a/model/web/auth/register/request.go +++ /dev/null @@ -1,17 +0,0 @@ -package register - -// Register Request Payload -// @Description Information that should be available when do a registration process -type RegisterRequestPayload struct { - // User Email - Email string `json:"email" validate:"required,email" example:"someone@example.com"` - - // User Password - Password string `json:"password" validate:"required" example:"secret"` - - // User Password Validation, must be same as user - PasswordValidation string `json:"password_validation" validate:"required,eqfield=Password" example:"secret"` - - // User name - Name string `json:"name" validate:"required" example:"someone"` -} diff --git a/model/web/error.go b/model/web/error.go deleted file mode 100644 index 2ef06063a41bdb0ebbcaf077dac124ae30dac97e..0000000000000000000000000000000000000000 --- a/model/web/error.go +++ /dev/null @@ -1,64 +0,0 @@ -package web - -import ( - "fmt" - - "github.com/go-playground/validator/v10" -) - -type ResponseError struct { - Message string `json:"-"` - Code string `json:"code"` - Details interface{} `json:"details"` -} - -func (v ResponseError) Error() string { - return v.Message -} - -func NewResponseError( - message string, - code string, -) ResponseError { - return ResponseError{ - Message: message, - Code: code, - Details: []string{}, - } -} - -func NewResponseErrorFromError( - err error, - code string, -) ResponseError { - return NewResponseError(err.Error(), code) -} - -func NewResponseErrorFromValidator( - err validator.ValidationErrors, -) ResponseError { - errList := []map[string]string{} - for _, err := range err { - errList = append(errList, map[string]string{ - "field": err.Field(), - "tag": err.Tag(), - }) - } - - return ResponseError{ - Message: "input is not valid", - Code: InvalidInput, - Details: errList, - } -} - -func NewResponseErrorf( - code string, - format string, - value ...interface{}, -) ResponseError { - return NewResponseErrorFromError( - fmt.Errorf(format, value...), - code, - ) -} diff --git a/model/web/error_code.go b/model/web/error_code.go deleted file mode 100644 index 0999a12b14af2383a1aea2f79dd7aa490754a88a..0000000000000000000000000000000000000000 --- a/model/web/error_code.go +++ /dev/null @@ -1,12 +0,0 @@ -package web - -const ( - InvalidInput string = "INVALID_INPUT" - - InvalidLogin string = "INVALID_LOGIN" - UnauthorizedAccess string = "UNAUTHORIZED" - InactiveUser string = "INACTIVE_ACCOUNT" - EmailExist string = "EMAIL_EXIST" - - TokenError string = "TOKEN_ERROR" -) diff --git a/provider/di.go b/provider/di.go deleted file mode 100644 index f1ffaae3f3d010c4ea5a836222e0efdaab8b9c76..0000000000000000000000000000000000000000 --- a/provider/di.go +++ /dev/null @@ -1,16 +0,0 @@ -package provider - -import ( - "github.com/google/wire" - "gitlab.informatika.org/ocw/ocw-backend/provider/mail" - "gitlab.informatika.org/ocw/ocw-backend/provider/mail/smtp" -) - -var ProviderSet = wire.NewSet( - // Provider - smtp.New, - mail.NewQueue, - - wire.Bind(new(mail.MailQueue), new(*mail.MailQueueImpl)), - wire.Bind(new(mail.MailProvider), new(*smtp.SmtpMailProvider)), -) diff --git a/provider/mail/queue.go b/provider/mail/queue.go deleted file mode 100644 index 84acd6815999beab1a5ad6fcd97781402b8c6896..0000000000000000000000000000000000000000 --- a/provider/mail/queue.go +++ /dev/null @@ -1,101 +0,0 @@ -package mail - -import ( - "context" - "fmt" - "sync" - "time" - - "gitlab.informatika.org/ocw/ocw-backend/service/logger" - "gitlab.informatika.org/ocw/ocw-backend/utils/env" -) - -type MailQueueImpl struct { - provider MailProvider - queue []Mail - mutex sync.Mutex - logUtil logger.Logger - env *env.Environment - isStarted bool -} - -func NewQueue( - provider MailProvider, - log logger.Logger, - env *env.Environment, -) *MailQueueImpl { - return &MailQueueImpl{ - provider: provider, - queue: []Mail{}, - mutex: sync.Mutex{}, - logUtil: log, - isStarted: false, - env: env, - } -} - -func (mq *MailQueueImpl) Send(mail Mail) { - if !mq.isStarted { - return - } - - mq.mutex.Lock() - defer mq.mutex.Unlock() - - mq.queue = append(mq.queue, mail) -} - -func (mq *MailQueueImpl) Flush() { - mq.mutex.Lock() - defer mq.mutex.Unlock() - - if len(mq.queue) == 0 { - return - } - - sendBuffer := make([]Mail, len(mq.queue)) - copy(sendBuffer, mq.queue) - - go func(buffer *[]Mail) { - for _, data := range *buffer { - err := mq.provider.Send(data.To, data.Subject, data.Message) - - if err != nil { - mq.logUtil.Error( - fmt.Sprintf("Problem with sending mail: %s", err.Error()), - ) - } - } - }(&sendBuffer) - - mq.queue = []Mail{} -} - -func (mq *MailQueueImpl) Start(ctx context.Context) { - go func() { - mq.isStarted = true - defer func() { - mq.isStarted = false - mq.logUtil.Info("🛑 Mail queue has been stopped.") - }() - - interval := time.Duration(mq.env.MailingInterval) - timer := time.NewTicker(interval * time.Millisecond) - defer timer.Stop() - - mq.logUtil.Info( - fmt.Sprintf("Mailing started to listen... (interval: %dms)", interval), - ) - - isLoop := true - - for isLoop { - select { - case <-ctx.Done(): - isLoop = false - case <-timer.C: - mq.Flush() - } - } - }() -} diff --git a/provider/mail/smtp/smtp.go b/provider/mail/smtp/smtp.go deleted file mode 100644 index dd2873a17083a7381fa3009679552d7dbd121590..0000000000000000000000000000000000000000 --- a/provider/mail/smtp/smtp.go +++ /dev/null @@ -1,44 +0,0 @@ -package smtp - -import ( - "fmt" - "net/smtp" - - "gitlab.informatika.org/ocw/ocw-backend/utils/env" -) - -type SmtpMailProvider struct { - *env.Environment - smtp.Auth -} - -func New(env *env.Environment) *SmtpMailProvider { - auth := smtp.PlainAuth( - env.SmtpIdentity, - env.SmtpUsername, - env.SmtpPassword, - env.SmtpServer, - ) - - return &SmtpMailProvider{ - Environment: env, - Auth: auth, - } -} - -func (s SmtpMailProvider) Send(to []string, subject string, message string) error { - payload := fmt.Sprintf( - "To: %s\r\n"+ - "Subject: %s\r\n"+ - "\r\n%s\r\n", - to, subject, message, - ) - - return smtp.SendMail( - fmt.Sprintf("%s:%d", s.SmtpServer, s.SmtpPort), - s.Auth, - s.SmtpUsername, - to, - []byte(payload), - ) -} diff --git a/provider/mail/type.go b/provider/mail/type.go deleted file mode 100644 index dbd185ef281d1f2ae39d09b8e15af75bc169c76e..0000000000000000000000000000000000000000 --- a/provider/mail/type.go +++ /dev/null @@ -1,19 +0,0 @@ -package mail - -import "context" - -type Mail struct { - To []string - Subject string - Message string -} - -type MailProvider interface { - Send(to []string, subject string, message string) error -} - -type MailQueue interface { - Send(mail Mail) - Flush() - Start(ctx context.Context) -} diff --git a/repository/user/type.go b/repository/user/type.go index 43ba1ea63681a21f2280674ff36bba5bc9db7146..047ee696b02aef9c583d3cd0ff7e18878e0f25e5 100644 --- a/repository/user/type.go +++ b/repository/user/type.go @@ -9,5 +9,4 @@ type UserRepository interface { Get(username string) (*user.User, error) Update(user user.User) error Delete(username string) error - IsExist(user string) (bool, error) } diff --git a/repository/user/user.go b/repository/user/user.go index 90858748ef449d00b5bfebf8fbe43f5c7564f343..881a4c6953af8c7e995fd6ea9e4b0e8fb6322923 100644 --- a/repository/user/user.go +++ b/repository/user/user.go @@ -1,8 +1,6 @@ package user import ( - "errors" - "gitlab.informatika.org/ocw/ocw-backend/model/domain/user" "gitlab.informatika.org/ocw/ocw-backend/utils/db" "gorm.io/gorm" @@ -18,27 +16,13 @@ func New( return &UserRepositoryImpl{db.Connect()} } -func (repo UserRepositoryImpl) IsExist(email string) (bool, error) { - _, err := repo.Get(email) - - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return true, nil - } - - return true, err - } - - return false, nil -} - func (repo UserRepositoryImpl) Add(user user.User) error { - return repo.db.Create(&user).Error + return repo.db.Create(user).Error } -func (repo UserRepositoryImpl) Get(email string) (*user.User, error) { +func (repo UserRepositoryImpl) Get(username string) (*user.User, error) { result := &user.User{} - err := repo.db.Where("email = ?", email).First(result).Error + err := repo.db.Where("username = ?", username).First(result).Error if err != nil { return nil, err @@ -51,6 +35,6 @@ func (repo UserRepositoryImpl) Update(user user.User) error { return repo.db.Save(user).Error } -func (repo UserRepositoryImpl) Delete(email string) error { - return repo.db.Where("email = ?", email).Delete(&user.User{}).Error +func (repo UserRepositoryImpl) Delete(username string) error { + return repo.db.Where("username = ?", username).Delete(&user.User{}).Error } diff --git a/routes/auth/route.go b/routes/auth/route.go index d7ea811b69fd604111f9a013b7821a10ef005619..55377de3603255eb0ab5ba3d0950dd8d5bfbcb4a 100644 --- a/routes/auth/route.go +++ b/routes/auth/route.go @@ -13,6 +13,5 @@ func (ar AuthRoutes) Register(r chi.Router) { r.Route("/auth", func(r chi.Router) { r.Post("/login", ar.AuthHandler.Login) r.Post("/refresh", ar.AuthHandler.Refresh) - r.Post("/register", ar.AuthHandler.Register) }) } diff --git a/service/auth/impl.go b/service/auth/impl.go index 9ac5f343fb68b92e44a3a51491389a21d5c70c5a..d8ddef7c19cfb3dcd80116be650c34a3d5b6256e 100644 --- a/service/auth/impl.go +++ b/service/auth/impl.go @@ -2,7 +2,6 @@ package auth import ( "gitlab.informatika.org/ocw/ocw-backend/repository/user" - "gitlab.informatika.org/ocw/ocw-backend/service/verification" "gitlab.informatika.org/ocw/ocw-backend/utils/env" "gitlab.informatika.org/ocw/ocw-backend/utils/password" "gitlab.informatika.org/ocw/ocw-backend/utils/token" @@ -11,7 +10,6 @@ import ( type AuthServiceImpl struct { user.UserRepository password.PasswordUtil - *env.Environment + env.Environment token.TokenUtil - verification.VerificationService } diff --git a/service/auth/login.go b/service/auth/login.go index 33d52237aec5b52a8a56796b5c410f54e0fe6189..0ed6024ef98e633119cabaaacac98709e875d155 100644 --- a/service/auth/login.go +++ b/service/auth/login.go @@ -2,24 +2,24 @@ package auth import ( "errors" + "fmt" "time" "github.com/golang-jwt/jwt/v4" - "gitlab.informatika.org/ocw/ocw-backend/model/web" "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/login" tokenModel "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/token" "gorm.io/gorm" ) func (auth AuthServiceImpl) Login(payload login.LoginRequestPayload) (*login.LoginResponsePayload, error) { - user, err := auth.UserRepository.Get(payload.Email) + user, err := auth.Get(payload.Email) if err != nil { var errorObj error switch { case errors.Is(err, gorm.ErrRecordNotFound): - errorObj = web.NewResponseError("username and password combination not found", web.InvalidLogin) + errorObj = fmt.Errorf("username and password combination not found") default: errorObj = err } @@ -28,11 +28,11 @@ func (auth AuthServiceImpl) Login(payload login.LoginRequestPayload) (*login.Log } if err := auth.Check(payload.Password, user.Password); err != nil { - return nil, web.NewResponseError("username and password combination not found", web.InvalidLogin) + return nil, fmt.Errorf("username and password combination not found") } if !user.IsActivated { - return nil, web.NewResponseError("user is not activated yet", web.InactiveUser) + return nil, fmt.Errorf("user is not activated yet") } refreshClaim := tokenModel.UserClaim{ @@ -59,12 +59,14 @@ func (auth AuthServiceImpl) Login(payload login.LoginRequestPayload) (*login.Log }, } - refreshToken, err := auth.TokenUtil.Generate(refreshClaim, auth.TokenUtil.DefaultMethod()) + refreshToken, err := auth.TokenUtil.Generate(refreshClaim) + if err != nil { return nil, err } - accessToken, err := auth.TokenUtil.Generate(accessClaim, auth.TokenUtil.DefaultMethod()) + accessToken, err := auth.TokenUtil.Generate(accessClaim) + if err != nil { return nil, err } diff --git a/service/auth/refresh.go b/service/auth/refresh.go index 02306777bf36ffa80375d9a0150a9199a3d62b6e..70aecd6488fc5d569a07cd7c9c5ab1cb9f6337a7 100644 --- a/service/auth/refresh.go +++ b/service/auth/refresh.go @@ -4,7 +4,6 @@ import ( "time" "github.com/golang-jwt/jwt/v4" - "gitlab.informatika.org/ocw/ocw-backend/model/web" "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/refresh" "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/token" ) @@ -13,13 +12,13 @@ func (auth AuthServiceImpl) Refresh(payload refresh.RefreshRequestPayload) (*ref claim, err := auth.TokenUtil.Validate(payload.RefreshToken, token.Refresh) if err != nil { - return nil, web.NewResponseErrorFromError(err, web.TokenError) + return nil, err } claim.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Duration(auth.TokenAccessExpired) * time.Millisecond)) claim.Type = token.Access - newToken, err := auth.TokenUtil.Generate(*claim, auth.TokenUtil.DefaultMethod()) + newToken, err := auth.TokenUtil.Generate(*claim) if err != nil { return nil, err diff --git a/service/auth/register.go b/service/auth/register.go deleted file mode 100644 index 6eb423b39900bb2502234c2558b0414a4e50f10c..0000000000000000000000000000000000000000 --- a/service/auth/register.go +++ /dev/null @@ -1,22 +0,0 @@ -package auth - -import ( - "gitlab.informatika.org/ocw/ocw-backend/model/domain/user" - "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/register" -) - -func (auth AuthServiceImpl) Register(payload register.RegisterRequestPayload) error { - err := auth.UserRepository.Add(user.User{ - Email: payload.Email, - Password: payload.Password, - Name: payload.Name, - Role: user.Student, - IsActivated: false, - }) - - if err == nil { - auth.SendVerifyMail(payload.Email) - } - - return err -} diff --git a/service/auth/type.go b/service/auth/type.go index 2503726fe0562e9b2b26544dabae60017d13c386..87a4615ba223ae43031005df40950cf550db5fcb 100644 --- a/service/auth/type.go +++ b/service/auth/type.go @@ -3,11 +3,9 @@ package auth import ( "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/login" "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/refresh" - "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/register" ) type AuthService interface { Login(payload login.LoginRequestPayload) (*login.LoginResponsePayload, error) Refresh(payload refresh.RefreshRequestPayload) (*refresh.RefreshResponsePayload, error) - Register(payload register.RegisterRequestPayload) error } diff --git a/service/di.go b/service/di.go index ee7d5e8ddb1c2c9074da8855c60d664e0882f760..b2eb205fb0c4b678f4846fb09d680eb2a0306d0b 100644 --- a/service/di.go +++ b/service/di.go @@ -7,7 +7,6 @@ import ( "gitlab.informatika.org/ocw/ocw-backend/service/logger" "gitlab.informatika.org/ocw/ocw-backend/service/logger/hooks" "gitlab.informatika.org/ocw/ocw-backend/service/reporter" - "gitlab.informatika.org/ocw/ocw-backend/service/verification" ) var ServiceTestSet = wire.NewSet( @@ -25,15 +24,9 @@ var ServiceTestSet = wire.NewSet( // auth service wire.NewSet( - wire.Struct(new(auth.AuthServiceImpl), "*"), + wire.Struct(new(auth.AuthServiceImpl)), wire.Bind(new(auth.AuthService), new(*auth.AuthServiceImpl)), ), - - // verification service - wire.NewSet( - wire.Struct(new(verification.VerificationServiceImpl), "*"), - wire.Bind(new(verification.VerificationService), new(*verification.VerificationServiceImpl)), - ), ) var ServiceSet = wire.NewSet( diff --git a/service/reporter/logtail.go b/service/reporter/logtail.go index 50d58d90d0172f84426acbf3cc51c1ca3efc67a1..db034e18f5b0f33cea3583cb78a35b198c9882e7 100644 --- a/service/reporter/logtail.go +++ b/service/reporter/logtail.go @@ -134,16 +134,7 @@ func (l *LogtailReporter) Start(ctx context.Context) { go func() { l.isStarted = true - defer func() { - l.isStarted = false - - l.logUtil.PrintFormattedOutput( - "Reporter has been stopped.", - "Report", - "info", - log.ForeGreen, - ) - }() + defer func() { l.isStarted = false }() defer l.Flush() interval := time.Duration(l.env.LogFlushInterval) @@ -157,12 +148,10 @@ func (l *LogtailReporter) Start(ctx context.Context) { log.ForeGreen, ) - isLoop := true - - for isLoop { + for { select { case <-ctx.Done(): - isLoop = false + break case <-timer.C: l.Flush() } diff --git a/service/verification/impl.go b/service/verification/impl.go deleted file mode 100644 index 94db17485a4173f2ad820bbc100685d06f00d9b5..0000000000000000000000000000000000000000 --- a/service/verification/impl.go +++ /dev/null @@ -1,11 +0,0 @@ -package verification - -import ( - "gitlab.informatika.org/ocw/ocw-backend/provider/mail" - "gitlab.informatika.org/ocw/ocw-backend/repository/user" -) - -type VerificationServiceImpl struct { - mail.MailQueue - user.UserRepository -} diff --git a/service/verification/send.go b/service/verification/send.go deleted file mode 100644 index 9f404a803958d11c9f10a121ceacfc7aa87318d6..0000000000000000000000000000000000000000 --- a/service/verification/send.go +++ /dev/null @@ -1,6 +0,0 @@ -package verification - -func (v VerificationServiceImpl) SendVerifyMail(email string) error { - // TODO - return nil -} diff --git a/service/verification/type.go b/service/verification/type.go deleted file mode 100644 index e6df1d1939e37be6abf399db52d68632e0924a4c..0000000000000000000000000000000000000000 --- a/service/verification/type.go +++ /dev/null @@ -1,6 +0,0 @@ -package verification - -type VerificationService interface { - SendVerifyMail(email string) error - SetVerification(email string, isVerified bool) error -} diff --git a/service/verification/verify.go b/service/verification/verify.go deleted file mode 100644 index b18ce1ecaa19fd332e495f81a8377b814a010246..0000000000000000000000000000000000000000 --- a/service/verification/verify.go +++ /dev/null @@ -1,6 +0,0 @@ -package verification - -func (v VerificationServiceImpl) SetVerification(email string, isVerified bool) error { - // TODO - return nil -} diff --git a/test/api.go b/test/api.go deleted file mode 100644 index b67503d1f08ec5f0a09053ad8741a638a9a226bb..0000000000000000000000000000000000000000 --- a/test/api.go +++ /dev/null @@ -1,11 +0,0 @@ -package test - -import ( - "gitlab.informatika.org/ocw/ocw-backend/test/db" - "gitlab.informatika.org/ocw/ocw-backend/utils/app" -) - -type ApiTestPack struct { - *db.MockDatabase - app.Server -} diff --git a/test/db/di.go b/test/db/di.go deleted file mode 100644 index e1a84e965cb97818bb3645a349eded41c0734c2a..0000000000000000000000000000000000000000 --- a/test/db/di.go +++ /dev/null @@ -1,11 +0,0 @@ -package db - -import ( - "github.com/google/wire" - "gitlab.informatika.org/ocw/ocw-backend/utils/db" -) - -var DbTestSet = wire.NewSet( - New, - wire.Bind(new(db.Database), new(*MockDatabase)), -) diff --git a/test/db/mock.go b/test/db/mock.go deleted file mode 100644 index 8e86aa035eb1cc7078b386bac144c31a3640405e..0000000000000000000000000000000000000000 --- a/test/db/mock.go +++ /dev/null @@ -1,32 +0,0 @@ -package db - -import ( - "github.com/DATA-DOG/go-sqlmock" - "gorm.io/driver/postgres" - "gorm.io/gorm" -) - -type MockDatabase struct { - db *gorm.DB - Mock sqlmock.Sqlmock -} - -func New() (*MockDatabase, error) { - db, mock, err := sqlmock.New() - - if err != nil { - return nil, err - } - - g, err := gorm.Open(postgres.New( - postgres.Config{ - Conn: db, - }, - ), &gorm.Config{}) - - return &MockDatabase{g, mock}, err -} - -func (m MockDatabase) Connect() *gorm.DB { - return m.db -} diff --git a/test/di.go b/test/di.go index 46c16536d7737ad0f00d0cfc4cfb4f99f0b75e07..9030d589cf278b3c0460d7c60045eb1c07fbc1be 100644 --- a/test/di.go +++ b/test/di.go @@ -8,29 +8,22 @@ import ( "gitlab.informatika.org/ocw/ocw-backend/handler" "gitlab.informatika.org/ocw/ocw-backend/middleware" - "gitlab.informatika.org/ocw/ocw-backend/provider" - "gitlab.informatika.org/ocw/ocw-backend/repository" "gitlab.informatika.org/ocw/ocw-backend/routes" "gitlab.informatika.org/ocw/ocw-backend/service" "gitlab.informatika.org/ocw/ocw-backend/service/logger" - "gitlab.informatika.org/ocw/ocw-backend/test/db" "gitlab.informatika.org/ocw/ocw-backend/utils" + "gitlab.informatika.org/ocw/ocw-backend/utils/app" "gitlab.informatika.org/ocw/ocw-backend/utils/env" ) -func CreateServer(logger logger.Logger, envTest *env.Environment) (*ApiTestPack, error) { +func CreateServer(logger logger.Logger, envTest *env.Environment) (app.Server, error) { wire.Build( - wire.Struct(new(ApiTestPack), "*"), - utils.UtilSetTest, - repository.RepositoryBasicSet, handler.HandlerSet, middleware.MiddlewareSet, routes.RoutesSet, service.ServiceTestSet, - db.DbTestSet, - provider.ProviderSet, ) return nil, nil diff --git a/test/utils/base.go b/test/utils/base.go index e744a1ff61ef13b5842d21561d746430e6f295f1..4a75e7745250daf15dc3ffdfbce8f83c22527fdc 100644 --- a/test/utils/base.go +++ b/test/utils/base.go @@ -4,20 +4,19 @@ import ( "net/http" "gitlab.informatika.org/ocw/ocw-backend/test" - "gitlab.informatika.org/ocw/ocw-backend/test/db" "gitlab.informatika.org/ocw/ocw-backend/utils/env" ) -func NewTestHandler() (http.Handler, *MockLogger, *db.MockDatabase, error) { +func NewTestHandler() (http.Handler, *MockLogger, error) { logger := NewMockLogger() handler, err := test.CreateServer(logger, &env.Environment{ AppEnvironment: "DEVELOPMENT", }) if err != nil { - return nil, nil, nil, err + return nil, nil, err } logger.CleanLog() - return handler.GetServer(), logger, handler.MockDatabase, nil + return handler.GetServer(), logger, nil } diff --git a/test/utils/executor.go b/test/utils/executor.go index ced02a1a5ca17d6578e2a8a51ccde8f31cdfac87..1b4fda663f3e7372703dd1f7107878f9bbaaf8a3 100644 --- a/test/utils/executor.go +++ b/test/utils/executor.go @@ -15,7 +15,7 @@ type RequestData struct { } func ExecuteJSON(reqData RequestData) (*http.Response, *MockLogger, error) { - r, log, _, err := NewTestHandler() + r, log, err := NewTestHandler() if err != nil { return nil, nil, err @@ -50,32 +50,3 @@ func ExecuteJSON(reqData RequestData) (*http.Response, *MockLogger, error) { return res, log, nil } - -func ExecuteJSONWithHandler(r http.Handler, reqData RequestData) (*http.Response, error) { - var req *http.Request - - if reqData.Data == nil { - req = httptest.NewRequest(reqData.Method, reqData.Endpoint, nil) - } else { - byteData, err := json.Marshal(reqData.Data) - - if err != nil { - return nil, err - } - - reader := bytes.NewReader(byteData) - req = httptest.NewRequest(reqData.Method, reqData.Endpoint, reader) - } - - if reqData.Headers != nil { - for key, value := range reqData.Headers { - req.Header.Add(key, value) - } - } - - rec := httptest.NewRecorder() - - r.ServeHTTP(rec, req) - - return rec.Result(), nil -} diff --git a/test/utils/password/password_test.go b/test/utils/password/password_test.go index 3ffa6e81349941d9532eaa4231ebc4a89db917f9..e7205b89ea1532365cda6a3814d4bd43ed6f510b 100644 --- a/test/utils/password/password_test.go +++ b/test/utils/password/password_test.go @@ -4,16 +4,11 @@ import ( "testing" "github.com/stretchr/testify/assert" - "gitlab.informatika.org/ocw/ocw-backend/utils/env" "gitlab.informatika.org/ocw/ocw-backend/utils/password" ) func TestPasswordHash(t *testing.T) { - obj := password.PasswordUtilImpl{ - Environment: &env.Environment{ - PasswordCost: 10, - }, - } + obj := password.PasswordUtilImpl{} t.Run("PasswordCanBeHashed", func(t *testing.T) { _, err := obj.Hash("admin") @@ -21,18 +16,9 @@ func TestPasswordHash(t *testing.T) { assert.Nil(t, err) }) - t.Run("PasswordHashMustBeDifferOnSamePass", func(t *testing.T) { - hash1, err := obj.Hash("admin") - assert.Nil(t, err) - - hash2, err := obj.Hash("admin") - assert.Nil(t, err) - - assert.NotEqual(t, hash1, hash2) - }) - t.Run("PasswordCanBeHashAndValidateCorrectly", func(t *testing.T) { hash, err := obj.Hash("admin") + assert.Nil(t, err) err = obj.Check("admin", hash) diff --git a/test/utils/token/token_test.go b/test/utils/token/token_test.go deleted file mode 100644 index 5f950ba6534563a7f3f27a740e55fd40a107c09a..0000000000000000000000000000000000000000 --- a/test/utils/token/token_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package token_test - -import ( - "testing" - "time" - - "github.com/golang-jwt/jwt/v4" - "github.com/stretchr/testify/assert" - "gitlab.informatika.org/ocw/ocw-backend/model/domain/user" - tokenData "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/token" - "gitlab.informatika.org/ocw/ocw-backend/utils/env" - "gitlab.informatika.org/ocw/ocw-backend/utils/token" -) - -func TestToken(t *testing.T) { - tokenObj := token.TokenUtilImpl{ - Environment: &env.Environment{ - TokenSecret: "secret", - TokenMethod: "hs512", - }, - } - - t.Run("UserTokenTest", func(t *testing.T) { - claim := tokenData.UserClaim{ - Name: "Someone", - Email: "someone@example.com", - Role: user.Student, - Type: tokenData.Refresh, - } - - token, err := tokenObj.Generate(claim, tokenObj.DefaultMethod()) - assert.Nil(t, err) - - extractedToken, err := tokenObj.Validate(token, tokenData.Refresh) - assert.Nil(t, err) - assert.NotNil(t, extractedToken) - - assert.Equal(t, claim, *extractedToken) - }) - - t.Run("UserTokenInvalidType", func(t *testing.T) { - claim := tokenData.UserClaim{ - Name: "Someone", - Email: "someone@example.com", - Role: user.Student, - Type: tokenData.Refresh, - } - - token, err := tokenObj.Generate(claim, tokenObj.DefaultMethod()) - assert.Nil(t, err) - - extractedToken, err := tokenObj.Validate(token, tokenData.Access) - assert.NotNil(t, err) - assert.Nil(t, extractedToken) - assert.Equal(t, err.Error(), "token type is not valid") - }) - - t.Run("UserTokenExpired", func(t *testing.T) { - claim := tokenData.UserClaim{ - Name: "Someone", - Email: "someone@example.com", - Role: user.Student, - Type: tokenData.Refresh, - RegisteredClaims: jwt.RegisteredClaims{ - ExpiresAt: jwt.NewNumericDate(time.Now()), - }, - } - - token, err := tokenObj.Generate(claim, tokenObj.DefaultMethod()) - assert.Nil(t, err) - - extractedToken, err := tokenObj.Validate(token, tokenData.Refresh) - assert.NotNil(t, err) - assert.Nil(t, extractedToken) - assert.Contains(t, err.Error(), "expired") - }) -} diff --git a/utils/app/app.go b/utils/app/app.go index fe944504503b0d188f8734d7af924282c8018b7a..03fb68309608095773735f47cfb51ec05bd5ad29 100644 --- a/utils/app/app.go +++ b/utils/app/app.go @@ -3,7 +3,6 @@ package app import ( "github.com/go-chi/chi/v5" "gitlab.informatika.org/ocw/ocw-backend/middleware" - "gitlab.informatika.org/ocw/ocw-backend/provider/mail" "gitlab.informatika.org/ocw/ocw-backend/routes" "gitlab.informatika.org/ocw/ocw-backend/service/logger" "gitlab.informatika.org/ocw/ocw-backend/service/reporter" @@ -19,7 +18,6 @@ type HttpServer struct { res res.Resource env *env.Environment reporter reporter.Reporter - mail mail.MailQueue middlewaresName []string } @@ -31,7 +29,6 @@ func New( logUtil log.LogUtils, res res.Resource, reporter reporter.Reporter, - mailqueue mail.MailQueue, ) *HttpServer { r := chi.NewRouter() @@ -52,6 +49,5 @@ func New( env: env, reporter: reporter, middlewaresName: middlewareName, - mail: mailqueue, } } diff --git a/utils/app/start.go b/utils/app/start.go index 239f31530d1475a671b677e570849d911750332a..1ea8ecd578c8aa85178ec5e9b2e18c50b566d10b 100644 --- a/utils/app/start.go +++ b/utils/app/start.go @@ -23,7 +23,6 @@ func (l *HttpServer) Start() { serverCtx, cancelServer := context.WithCancel(context.Background()) l.reporter.Start(serverCtx) - l.mail.Start(serverCtx) sig := make(chan os.Signal, 3) signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) diff --git a/utils/db/database.go b/utils/db/database.go index 66f170bd385d3cc89d2ccefc9a243eac7def74cf..cf7545443c36da981607f993b2afd9b39af051d7 100644 --- a/utils/db/database.go +++ b/utils/db/database.go @@ -1,12 +1,8 @@ package db import ( - "fmt" - "os" - "runtime/debug" - "strings" + "database/sql" - "gitlab.informatika.org/ocw/ocw-backend/service/logger" "gitlab.informatika.org/ocw/ocw-backend/utils/env" "gorm.io/driver/postgres" "gorm.io/gorm" @@ -16,29 +12,23 @@ type DatabaseImpl struct { DB *gorm.DB } -func resolver(log logger.Logger) { - if rec := recover(); rec != nil { - log.Error("Some panic occured when processing request:") - log.Error(fmt.Sprint(rec)) - log.Error("") - - log.Error("Stack Trace:") - stacks := strings.Split(string(debug.Stack()), "\n") - - for _, val := range stacks { - log.Error(val) - } +func NewPostgresConn( + conn *sql.Conn, +) (*DatabaseImpl, error) { + res, err := gorm.Open(postgres.New(postgres.Config{ + Conn: conn, + }), &gorm.Config{}) - os.Exit(-1) + if err != nil { + return nil, err } + + return &DatabaseImpl{res}, nil } func NewPostgresEnv( - env *env.Environment, - log logger.Logger, + env env.Environment, ) (*DatabaseImpl, error) { - defer resolver(log) - res, err := gorm.Open(postgres.Open(env.DatabaseConnection), &gorm.Config{}) if err != nil { diff --git a/utils/di.go b/utils/di.go index 83aae428e68d27093cd90e32c4c1e9dbce765c59..5b8ac4d17ddce29b51d5b29cf86923f76d0abb51 100644 --- a/utils/di.go +++ b/utils/di.go @@ -14,6 +14,10 @@ import ( "gitlab.informatika.org/ocw/ocw-backend/utils/wrapper" ) +var DatabaseTestingSet = wire.NewSet( + db.NewPostgresConn, +) + var UtilSetTest = wire.NewSet( // httputil utility wire.Struct(new(httputil.HttpUtilImpl), "*"), @@ -49,12 +53,12 @@ var UtilSetTest = wire.NewSet( ) var UtilSet = wire.NewSet( - // env - env.New, - UtilSetTest, // Database utility wire.Bind(new(db.Database), new(*db.DatabaseImpl)), db.NewPostgresEnv, + + // env + env.New, ) diff --git a/utils/env/env.go b/utils/env/env.go index a55416e52bf462568666b3b4de1afc886d97fa44..1112fb6d6706e4b17edceac36b75c03d420db32b 100644 --- a/utils/env/env.go +++ b/utils/env/env.go @@ -27,15 +27,6 @@ type Environment struct { TokenRefreshExpired int64 `env:"TOKEN_REFRESH_EXPIRED_MS" envDefault:"86400000"` TokenAccessExpired int64 `env:"TOKEN_ACCESS_EXPIRED_MS" envDefault:"300000"` TokenIssuer string `env:"TOKEN_ISSUER" envDefault:"ocw"` - - MailingProvider string `env:"MAIL_PROVIDER" envDefault:"smtp"` - MailingInterval int64 `env:"MAIL_INTERVAL_MS" envDefault:"1000"` - - SmtpIdentity string `env:"SMTP_IDENTITY"` - SmtpUsername string `env:"SMTP_USERNAME"` - SmtpPassword string `env:"SMTP_PASSWORD"` - SmtpServer string `env:"SMTP_SERVER"` - SmtpPort int `env:"SMTP_PORT" envDefault:"25"` } func New() (*Environment, error) { diff --git a/utils/password/impl.go b/utils/password/impl.go index 63a6ed20648fa01054660b811adb1af7822a416e..9a660b472041db250ca4f6664ebb461db0560f39 100644 --- a/utils/password/impl.go +++ b/utils/password/impl.go @@ -3,12 +3,14 @@ package password import ( "fmt" + "gitlab.informatika.org/ocw/ocw-backend/utils/base64" "gitlab.informatika.org/ocw/ocw-backend/utils/env" "golang.org/x/crypto/bcrypt" ) type PasswordUtilImpl struct { - *env.Environment + env.Environment + base64.Base64Util } func (e PasswordUtilImpl) Hash(password string) (string, error) { diff --git a/utils/token/impl.go b/utils/token/impl.go index 3f026c5de86d524fd60f113b55feac678ff3cfee..9dde3aa95fc02d9be6e1e968ce62f0178da26080 100644 --- a/utils/token/impl.go +++ b/utils/token/impl.go @@ -9,10 +9,10 @@ import ( ) type TokenUtilImpl struct { - *env.Environment + env.Environment } -func (t TokenUtilImpl) DefaultMethod() jwt.SigningMethod { +func (t TokenUtilImpl) Method() jwt.SigningMethod { switch t.TokenMethod { case "hs256": return jwt.SigningMethodHS256 @@ -22,36 +22,32 @@ func (t TokenUtilImpl) DefaultMethod() jwt.SigningMethod { } func (tu TokenUtilImpl) Validate(tokenString string, tokenType token.TokenType) (*token.UserClaim, error) { - jwtData, err := jwt.ParseWithClaims(tokenString, &token.UserClaim{}, func(t *jwt.Token) (interface{}, error) { + jwtData, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) { if method, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("invalid signing method") - } else if method != tu.DefaultMethod() { + } else if method != tu.Method() { return nil, fmt.Errorf("invalid signing method") } - return []byte(tu.Environment.TokenSecret), nil + return tu.Method(), nil }) if err != nil { return nil, err } - claims, ok := jwtData.Claims.(*token.UserClaim) - - if !ok { - return nil, fmt.Errorf("invalid claim") - } + claims := jwtData.Claims.(*token.UserClaim) if claims.Type != tokenType { - return nil, fmt.Errorf("token type is not valid") + return claims, fmt.Errorf("token type is not valid") } return claims, nil } -func (t TokenUtilImpl) Generate(claim token.UserClaim, method jwt.SigningMethod) (string, error) { +func (t TokenUtilImpl) Generate(claim token.UserClaim) (string, error) { token := jwt.NewWithClaims( - method, + jwt.SigningMethodHS512, claim, ) diff --git a/utils/token/type.go b/utils/token/type.go index d338aad223926ef45a93871ee0c61b570f2c705f..cd6c27a2469bf7357953a88744a7609e307e02a2 100644 --- a/utils/token/type.go +++ b/utils/token/type.go @@ -1,12 +1,10 @@ package token import ( - "github.com/golang-jwt/jwt/v4" "gitlab.informatika.org/ocw/ocw-backend/model/web/auth/token" ) type TokenUtil interface { Validate(jwt string, tokenType token.TokenType) (*token.UserClaim, error) - Generate(claim token.UserClaim, method jwt.SigningMethod) (string, error) - DefaultMethod() jwt.SigningMethod + Generate(claim token.UserClaim) (string, error) }