Skip to content

Commit

Permalink
Merge pull request #20 from wzslr321/users-ms-tests
Browse files Browse the repository at this point in the history
Users ms tests
  • Loading branch information
wzslr321 committed Sep 10, 2021
2 parents 31fcf49 + 445ad55 commit a29089d
Show file tree
Hide file tree
Showing 19 changed files with 392 additions and 78 deletions.
12 changes: 6 additions & 6 deletions server/users/cmd/app/main.go
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
cors "github.com/rs/cors/wrapper/gin"
"github.com/wzslr321/artiver/server/user/entity"
"github.com/wzslr321/artiver/server/user/settings"
Expand All @@ -16,23 +17,22 @@ import (
"time"
)


type application struct {
users *entity.UserCollection
}

var app *application

const devConfig = "/conf/conf_dev.ini"

func init() {
settings.InitSettings()
_ = settings.InitSettings(devConfig)
}


func main() {

oc := options.Client().ApplyURI(settings.MongodbSettings.Uri)


client, err := mongo.NewClient(oc)
if err != nil {
log.Printf("Error occured while initializing a new mongo client: %v", err)
Expand All @@ -54,7 +54,6 @@ func main() {

log.Println("Successfully connected to the database!")


app = &application{
users: &entity.UserCollection{
C: client.Database("artiver").Collection("users"),
Expand All @@ -66,8 +65,10 @@ func main() {
readTimeout := settings.ServerSettings.ReadTimeout
writeTimeout := settings.ServerSettings.WriteTimeout
maxHeaderBytes := settings.ServerSettings.MaxHeaderBytes
runMode := settings.ServerSettings.RunMode

router.Use(cors.Default())
gin.SetMode(runMode)

server := &http.Server{
Addr: address,
Expand All @@ -89,7 +90,6 @@ func main() {

quit := make(chan os.Signal)


signal.Notify(make(chan os.Signal, 1), syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down the server...")
Expand Down
2 changes: 1 addition & 1 deletion server/users/cmd/app/router.go
Expand Up @@ -5,7 +5,7 @@ import (
cors "github.com/rs/cors/wrapper/gin"
)


// InitRouter is test for godoc.
func (app *application) InitRouter() *gin.Engine {
r := gin.New()

Expand Down
60 changes: 42 additions & 18 deletions server/users/cmd/app/user.go
Expand Up @@ -3,31 +3,38 @@ package main
import (
"github.com/gin-gonic/gin"
"github.com/wzslr321/artiver/server/user/presenter"
"log"
"net/http"
)

func (app *application) createUser(ctx *gin.Context) {
// ⚠️ Naming definitely requires major changes ⚠️

var json presenter.Register
if err := ctx.ShouldBindJSON(&json); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
func (app *application) createUser(ctx *gin.Context) {

user, err := app.users.NewUser(json.Email, json.Username, json.Password)
if err != nil {
log.Fatalf("Failed to create a new user: %v", err)
return
}
var json presenter.Register

if err := ctx.ShouldBindJSON(&json); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": "Failed to create a new user due to incorrect request body",
"error": err.Error(),
})
return
}

ctx.JSON(http.StatusOK, gin.H{
"message":"Successfully created new user",
"user": user,
user, err := app.users.NewUser(json.Email, json.Username, json.Password)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"message": "Failed to create a new user",
"error": err,
})
return
}

ctx.JSON(http.StatusOK, gin.H{
"message": "Successfully created new user",
"user": user,
})

return
}

func (app *application) getUserByUsername(ctx *gin.Context) {
Expand Down Expand Up @@ -70,4 +77,21 @@ func (app *application) updateUser(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"respond": res,
})
}
}

func (app *application) signIn(ctx *gin.Context) {
var json presenter.User
if err := ctx.ShouldBindJSON(&json); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}

user, err := app.users.LoginUser(json.Email, json.Password)
if err != nil {
return
}

token, refreshToken, _ :=
}
3 changes: 2 additions & 1 deletion server/users/conf/conf_dev.ini
@@ -1,8 +1,9 @@
[server]
RunMode = "debug"
Address = 8081
ReadTimeout = 60
WriteTimeout = 60
MaxHeaderBytes = 1 << 20

[mongodb]
Uri = mongodb://root:example@mongodb:27017
Uri = mongodb://root:example@mongodb:27017
9 changes: 9 additions & 0 deletions server/users/conf/conf_prod.ini
@@ -0,0 +1,9 @@
[server]
RunMode = "release"
Address = 8081
ReadTimeout = 60
WriteTimeout = 60
MaxHeaderBytes = 1 << 20

[mongodb]
Uri = mongodb://root:example@mongodb:27017
6 changes: 3 additions & 3 deletions server/users/conf/path.go
Expand Up @@ -5,9 +5,9 @@ import (
"runtime"
)

func GetRootDir() string {
_, b, _, _ := runtime.Caller(0)
func GetConfDir() (string, bool) {
_, b, _, ok := runtime.Caller(0)
basePath := filepath.Dir(b)

return filepath.Dir(basePath)
return filepath.Dir(basePath), ok
}
12 changes: 12 additions & 0 deletions server/users/conf/path_test.go
@@ -0,0 +1,12 @@
package conf

import (
"github.com/stretchr/testify/assert"
"testing"
)

func TestGetConfDir(t *testing.T) {
result, ok := GetConfDir()
assert.NotEmpty(t, result)
assert.IsType(t, ok, true)
}
5 changes: 3 additions & 2 deletions server/docs/Dockerfile → server/users/docs/Dockerfile
@@ -1,9 +1,10 @@
FROM golang:alpine

WORKDIR /docs/server

WORKDIR /go/src/users

RUN go get golang.org/x/tools/cmd/godoc

COPY . .

CMD ["godoc", "-http=:8080"]
CMD ["godoc", "-http=:8082"]
41 changes: 35 additions & 6 deletions server/users/entity/user_methods.go
Expand Up @@ -12,25 +12,33 @@ import (
)

func (m *UserCollection) NewUser(email, username, password string) (*User, error) {
uuid := pkg.GenerateID()
uuid, err := pkg.GenerateID()
if err != nil {
return nil, err
}

id := ID(uuid)

pwd, err := pkg.GeneratePasswordHash(password)
var pwd string
pwd, err = pkg.GeneratePasswordHash(password)
if err != nil {
return nil, err
}

u := &User{
ID: id,
Email: email,
Username: username,
Password: pwd,
Email: &email,
Username: &username,
Password: &pwd,
CreatedAt: time.Now(),
}

err = validate(email, username, password)
var isOK bool
isOK, err = Validate(email, username, password)
if err != nil {
return nil, err
} else if isOK != true {
return nil, ValidationError
}

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
Expand Down Expand Up @@ -153,3 +161,24 @@ func (m *UserCollection) UpdateUser(user *presenter.User) bson.M {

return updatedUser
}

func (m *UserCollection) LoginUser(email, password string) (*User, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

var foundUser *User

if err := m.C.FindOne(ctx, bson.M{"email": email}).Decode(&foundUser); err != nil {
return nil, err
}

isPasswordValid, err := pkg.VerifyPassword(password, *foundUser.Password)
if !isPasswordValid {
return nil, nil
} else if err != nil {
return nil, nil
}

return foundUser, nil

}
16 changes: 9 additions & 7 deletions server/users/entity/user_structs.go
Expand Up @@ -14,20 +14,22 @@ type UserCollection struct {

type User struct {
ID ID
Email string
Password string
Username string
Email *string
Password *string
Username *string
CreatedAt time.Time
UpdatedAt time.Time
// Preferences are an array of keywords that are used to filter and personalize articles.
Preferences []string
Preferences *[]string
// Liked articles - contains an array of ID to make it more effective
// than storing whole articles. IDs will be simply used as a reference.
Liked []ID
Liked *[]ID
// Articles - List of articles written by user. Holds an array of IDs
// to use them as a reference.
Articles []ID
Articles *[]ID
// Reviews - List of reviews written by user. Holds an array of IDs
// to use them as a reference.
Reviews []ID
Reviews []ID
Token *string
RefreshToken *string
}

0 comments on commit a29089d

Please sign in to comment.