diff --git a/go.mod b/go.mod index 1a73900..14854e4 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.19 require github.com/sirupsen/logrus v1.9.0 require ( + github.com/golang-jwt/jwt/v5 v5.0.0-rc.2 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/pgconn v1.14.0 // indirect github.com/jackc/pgio v1.0.0 // indirect @@ -29,8 +30,8 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/stretchr/objx v0.5.0 // indirect github.com/stretchr/testify v1.8.1 // indirect - golang.org/x/crypto v0.6.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 61dad56..6c79231 100644 --- a/go.sum +++ b/go.sum @@ -11,6 +11,8 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/golang-jwt/jwt/v5 v5.0.0-rc.2 h1:hXPcSazn8wKOfSb9y2m1bdgUMlDxVDarxh3lJVbC6JE= +github.com/golang-jwt/jwt/v5 v5.0.0-rc.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= @@ -151,6 +153,8 @@ golang.org/x/crypto v0.4.0 h1:UVQgzMY87xqpKNgb+kDsll2Igd33HszWHFLmpaRMq/8= golang.org/x/crypto v0.4.0/go.mod h1:3quD/ATkf6oY+rnes5c3ExXTbLc8mueNue5/DoinL80= golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= @@ -186,6 +190,8 @@ golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -200,6 +206,8 @@ golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= diff --git a/internal/bd/filmsrepo.go b/internal/bd/filmsrepo.go index 5970d55..9b65348 100644 --- a/internal/bd/filmsrepo.go +++ b/internal/bd/filmsrepo.go @@ -92,7 +92,7 @@ func (f *Filmsrepo) FindById(id string) (*model.Films, error) { func (f *Filmsrepo) FindByName(name string) (*[]model.Films, error) { var films []model.Films - rows, err := f.db.db.Query(context.Background(), "SELECT * FROM films WHERE ru_title LIKE %$1%;", name) + rows, err := f.db.db.Query(context.Background(), "SELECT id, Ru_title, year, posterurl, content_type FROM films WHERE ru_title LIKE $1;", "%"+name+"%") if err != nil { return nil, err } @@ -100,10 +100,7 @@ func (f *Filmsrepo) FindByName(name string) (*[]model.Films, error) { defer rows.Close() for rows.Next() { var film model.Films - err = rows.Scan(&film.Id, &film.Ru_title, &film.Orig_title, &film.Imdb_id, &film.Kinopoisk_id, - &film.PosterUrl, &film.PosterUrlPreview, &film.Countries, &film.Genres, &film.Year, - &film.Description, &film.RatingKinopoisk, &film.RatingImdb, &film.Iframe_src, &film.RatingImdbVoteCount, - &film.RatingKinopoiskVoteCount, &film.Created, &film.Media) + err = rows.Scan(&film.Id, &film.Ru_title, &film.Year, &film.PosterUrl, &film.Contenttype) if err != nil { return nil, err } diff --git a/internal/bd/model/user.go b/internal/bd/model/user.go index 03f90c4..3caa0b1 100644 --- a/internal/bd/model/user.go +++ b/internal/bd/model/user.go @@ -2,10 +2,9 @@ package model type User struct { Id int - Login string - Email string - Password string + Login string `json:"login"` + Email string `json:"email"` + Password string `json:"password"` Avatar_Url string - Token string PermisionLVL int } diff --git a/internal/bd/siriesrepo.go b/internal/bd/siriesrepo.go index 4f40e6d..3ac4d77 100644 --- a/internal/bd/siriesrepo.go +++ b/internal/bd/siriesrepo.go @@ -125,17 +125,14 @@ func (s *Siriesrepo) FindByAll() (*[]model.Siries, error) { func (s *Siriesrepo) FindByName(name string) (*[]model.Siries, error) { var buffs []model.Siries - rows, err := s.db.db.Query(context.Background(), "SELECT * FROM siries WHERE ru_title LIKE $1", "%"+name+"%") + rows, err := s.db.db.Query(context.Background(), "SELECT id, Ru_title, year, posterurl, content_type FROM siries WHERE ru_title LIKE $1;", "%"+name+"%") if err != nil { return nil, err } defer rows.Close() for rows.Next() { var buff model.Siries - err = rows.Scan(&buff.Id, &buff.Ru_title, &buff.Orig_title, &buff.Imdb_id, &buff.Kinopoisk_id, - &buff.PosterUrl, &buff.PosterUrlPreview, &buff.Countries, &buff.Genres, &buff.Year, - &buff.Description, &buff.RatingKinopoisk, &buff.RatingImdb, &buff.Iframe_src, &buff.RatingImdbVoteCount, - &buff.RatingKinopoiskVoteCount, &buff.Created, &buff.Translations, &buff.Episodes) + err = rows.Scan(&buff.Id, &buff.Ru_title, &buff.Year, &buff.PosterUrl, &buff.Contenttype) if err != nil { return nil, err } diff --git a/internal/bd/userrepo.go b/internal/bd/userrepo.go index b8ac9de..ac04cbb 100644 --- a/internal/bd/userrepo.go +++ b/internal/bd/userrepo.go @@ -11,27 +11,55 @@ type Userrepo struct { db Bd } -func (u *Userrepo) Create(user *model.User) (*model.User, error) { - err := u.db.db.QueryRow(context.Background(), - "INSERT INTO users (id, login, email, password, avatar_url, token, permisionlvl) VALUES($1, $2, $3, $4, $5, $6, $7) RETURNING id, permisionlvl", user.Id, user.Login, user.Email, user.Password, user.Avatar_Url, user.Token, user.PermisionLVL). - Scan(&user.Id, &user.PermisionLVL) +func (u *Userrepo) Create(user *model.User) error { + _, err := u.db.db.Exec(context.Background(), + "INSERT INTO users (login, email, password, permisionlvl) VALUES($1, $2, $3, $4)", user.Login, user.Email, user.Password, user.PermisionLVL) if err != nil { - return nil, err + return err } - return user, nil + return nil } func (u *Userrepo) FindById(id string) (*model.User, error) { var user model.User query := fmt.Sprintf("SELECT * FROM users WHERE Id = %s;", id) err := u.db.db.QueryRow(context.Background(), query). - Scan(user.Id, user.Login, user.Email, user.Password, user.Avatar_Url, user.Token, user.PermisionLVL) + Scan(user.Id, user.Login, user.Email, user.Password, user.Avatar_Url, user.PermisionLVL) if err != nil { return nil, err } return &user, nil } +func (u *Userrepo) FindByLogin(login string) (*model.User, error) { + var user model.User + rows, err := u.db.db.Query(context.Background(), "SELECT login FROM users WHERE login = $1", login) + + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + err = rows.Scan(&user.Login) + } + return &user, nil + +} + +func (u *Userrepo) FindByEmail(email string) (*model.User, error) { + var user model.User + rows, err := u.db.db.Query(context.Background(), "SELECT email FROM users WHERE email = $1", email) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + err = rows.Scan(&user.Email) + } + return &user, nil + +} + func (u *Userrepo) FindByAll() (*model.User, error) { return nil, nil } diff --git a/internal/restserver/filmhandle.go b/internal/restserver/filmhandle.go index 230f987..dfa164c 100644 --- a/internal/restserver/filmhandle.go +++ b/internal/restserver/filmhandle.go @@ -31,6 +31,8 @@ func (r *RestServer) HandleHello() http.HandlerFunc { } w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) io.WriteString(w, strconv.Itoa(*cout)) } } @@ -62,21 +64,33 @@ func (r *RestServer) HendleFindAll() http.HandlerFunc { func (r *RestServer) HeandleFilmsFindName() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") name := mux.Vars(res)["name"] films, err := r.db.Films().FindByName(name) if err != nil { r.logger.Errorln(err) } - jsonData, err := json.Marshal(films) - if err != nil { - r.logger.Errorln(err) + if *films != nil { + jsonData, err := json.Marshal(films) + if err != nil { + r.logger.Errorln(err) + } + io.WriteString(w, string(jsonData)) + } else { + io.WriteString(w, string(`[]`)) } - io.WriteString(w, string(jsonData)) + } } func (r *RestServer) HeandleFilmsSortGenres() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") name := mux.Vars(res)["name"] films, err := r.db.Films().SortByGanres(name) if err != nil { @@ -92,6 +106,9 @@ func (r *RestServer) HeandleFilmsSortGenres() http.HandlerFunc { func (r *RestServer) HendleFindID() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") id := mux.Vars(res)["id"] fmt.Println(mux.Vars(res)) film, err := r.db.Films().FindById(id) @@ -102,14 +119,16 @@ func (r *RestServer) HendleFindID() http.HandlerFunc { if err != nil { r.logger.Errorln(err) } - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + io.WriteString(w, string(jsonData)) } } func (r *RestServer) HendlePagination() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") id := mux.Vars(res)["page"] films, err := r.db.Films().Pagination(id) if err != nil { @@ -119,8 +138,6 @@ func (r *RestServer) HendlePagination() http.HandlerFunc { if err != nil { r.logger.Errorln(err) } - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type") io.WriteString(w, string(jsondata)) } @@ -128,6 +145,9 @@ func (r *RestServer) HendlePagination() http.HandlerFunc { func (r *RestServer) HeadleGetLastItem() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") films, err := r.db.Films().LastItem() if err != nil { r.logger.Errorln(err) @@ -136,8 +156,6 @@ func (r *RestServer) HeadleGetLastItem() http.HandlerFunc { if err != nil { r.logger.Errorln(err) } - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type") io.WriteString(w, string(jsondata)) } } diff --git a/internal/restserver/restserver.go b/internal/restserver/restserver.go index f8676af..a56f41a 100644 --- a/internal/restserver/restserver.go +++ b/internal/restserver/restserver.go @@ -8,6 +8,13 @@ import ( "github.com/sirupsen/logrus" ) +const ( + ContextKeyUser = iota + defaultPermLvl = 1 + writerPermLvl = 2 + adminPermLvl = 3 +) + type RestServer struct { config *Config logger *logrus.Logger diff --git a/internal/restserver/siriesheandle.go b/internal/restserver/siriesheandle.go index 1a3d41e..08bc207 100644 --- a/internal/restserver/siriesheandle.go +++ b/internal/restserver/siriesheandle.go @@ -23,14 +23,15 @@ func (r *RestServer) configureRouterSiries() { func (r *RestServer) HandleHelloSiries() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") id := res.URL.Query().Get("id") fmt.Println(id) cout, err := r.db.Siries().GetCountFilms() if err != nil { r.logger.Errorln(err) } - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type") io.WriteString(w, strconv.Itoa(*cout)) } } @@ -62,21 +63,32 @@ func (r *RestServer) HendleFindAllSiries() http.HandlerFunc { func (r *RestServer) HeandleSiriesFindName() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") name := mux.Vars(res)["name"] siries, err := r.db.Siries().FindByName(name) if err != nil { r.logger.Errorln(err) } - jsonData, err := json.Marshal(siries) - if err != nil { - r.logger.Errorln(err) + if *siries != nil { + jsonData, err := json.Marshal(siries) + if err != nil { + r.logger.Errorln(err) + } + io.WriteString(w, string(jsonData)) + } else { + io.WriteString(w, string(`[]`)) } - io.WriteString(w, string(jsonData)) + } } func (r *RestServer) HeandleSiriesSortGenres() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") name := mux.Vars(res)["name"] siries, err := r.db.Siries().SortByGanres(name) if err != nil { @@ -92,6 +104,9 @@ func (r *RestServer) HeandleSiriesSortGenres() http.HandlerFunc { func (r *RestServer) HendleFindIDSiries() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") id := mux.Vars(res)["id"] fmt.Println(mux.Vars(res)) siries, err := r.db.Siries().FindById(id) @@ -102,14 +117,15 @@ func (r *RestServer) HendleFindIDSiries() http.HandlerFunc { if err != nil { r.logger.Errorln(err) } - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type") io.WriteString(w, string(jsonData)) } } func (r *RestServer) HendlePaginationSiries() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") id := mux.Vars(res)["page"] siries, err := r.db.Siries().Pagination(id) if err != nil { @@ -119,8 +135,6 @@ func (r *RestServer) HendlePaginationSiries() http.HandlerFunc { if err != nil { r.logger.Errorln(err) } - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type") io.WriteString(w, string(jsondata)) } @@ -128,6 +142,9 @@ func (r *RestServer) HendlePaginationSiries() http.HandlerFunc { func (r *RestServer) HeadleGetLastItemSiries() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") siries, err := r.db.Siries().LastItem() if err != nil { r.logger.Errorln(err) @@ -136,8 +153,6 @@ func (r *RestServer) HeadleGetLastItemSiries() http.HandlerFunc { if err != nil { r.logger.Errorln(err) } - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type") io.WriteString(w, string(jsondata)) } } diff --git a/internal/restserver/userHendle.go b/internal/restserver/userHendle.go index 76eeaf5..0c34c2e 100644 --- a/internal/restserver/userHendle.go +++ b/internal/restserver/userHendle.go @@ -1,36 +1,49 @@ package restserver import ( + "fmt" + "io" "net/http" "git.ukamnya.ru/stulyaganov/RestApiv2/internal/bd/model" + "git.ukamnya.ru/stulyaganov/RestApiv2/pkg/utils/password" ) func (r *RestServer) configureRouterUser() { - r.router.HandleFunc("/api/register", r.HandleFuncRegUser()).Methods("POST") + r.router.HandleFunc("/api/register", r.chekUserRegistr(r.HandleFuncRegUser())).Methods("POST") + r.router.HandleFunc("/api/login", r.HandleFuncLoginUser()).Methods("POST") + r.router.HandleFunc("/api/logout", r.HandleFuncLogOutUser()).Methods("POST") } func (r *RestServer) HandleFuncRegUser() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { - user := model.User{} - err := res.ParseForm() + users := res.Context().Value(ContextKeyUser).(*model.User) + + hash, err := password.HashPassword(users.Password) + if err != nil { r.logger.Error(err) } - user.Id = 1 - user.Login = res.Form.Get("user") - user.Password = res.Form.Get("password") - user.Email = res.Form.Get("email") - user.PermisionLVL = 1 - user.Token = "dasf2!23sfafaQWerq" - - RetUser, err := r.db.User().Create(&user) + users.Password = string(*hash) + err = r.db.User().Create(users) if err != nil { - r.logger.Errorln(err) - } - if RetUser != nil { - r.logger.Infoln("Create new user with id = ", RetUser.Id, " and with permissionLvl = ", RetUser.Id) + r.logger.Error(err) + } else { + io.WriteString(w, `{"data":"Пользователь создан"}`) } + } } + +func (r *RestServer) HandleFuncLoginUser() http.HandlerFunc { + return func(w http.ResponseWriter, res *http.Request) { + fmt.Println("login") + } +} + +func (r *RestServer) HandleFuncLogOutUser() http.HandlerFunc { + return func(w http.ResponseWriter, res *http.Request) { + fmt.Println("login") + } +} diff --git a/internal/restserver/usermidleware.go b/internal/restserver/usermidleware.go new file mode 100644 index 0000000..bdb450f --- /dev/null +++ b/internal/restserver/usermidleware.go @@ -0,0 +1,49 @@ +package restserver + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + + "git.ukamnya.ru/stulyaganov/RestApiv2/internal/bd/model" + "git.ukamnya.ru/stulyaganov/RestApiv2/pkg/utils/validator" +) + +func (r *RestServer) chekUserRegistr(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, res *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Content-Type", "application/json") + users := &model.User{} + valid := validator.NewValidator(8, 32, 1) + err := json.NewDecoder(res.Body).Decode(users) + if err != nil { + r.logger.Error(err) + } + user, err := r.db.User().FindByLogin(users.Login) + if err != nil { + r.logger.Error(err) + } + if user.Login != "" { + io.WriteString(w, `{"data":"Такой Логин уже занят попробуйте придумать другой"}`) + return + } + user, err = r.db.User().FindByEmail(users.Email) + if err != nil { + r.logger.Error(err) + return + } + if user.Email != "" { + io.WriteString(w, `{"data":"Такой email уже используется другим пользователем"}`) + return + } + _, err = valid.CheckValid(users.Password) + if err != nil { + io.WriteString(w, fmt.Sprintf(`{"data":"%s"}`, err)) + return + } + next(w, res.WithContext(context.WithValue(res.Context(), ContextKeyUser, users))) + } +} diff --git a/migrates/20221213130458_films.up.sql b/migrates/20221213130458_films.up.sql index a172a74..96a8197 100644 --- a/migrates/20221213130458_films.up.sql +++ b/migrates/20221213130458_films.up.sql @@ -22,12 +22,20 @@ CREATE TABLE films ( ); CREATE TABLE users ( - id INTEGER NOT NULL, - login VARCHAR(25) not NULL, - email VARCHAR(255) NOT NULL, - password VARCHAR(2500) NOT NULL, - avatar_url VARCHAR(2500), - token VARCHAR(2500) NOT NULL, + id SERIAL, + login TEXT not NULL, + email TEXT NOT NULL, + password TEXT NOT NULL, + avatar_url TEXT, permisionLVL INTEGER NOT NULL, + SaveItem INTEGER Array, + LaterItem INTEGER Array, + WantItem INTEGER Array, PRIMARY KEY(id) ); + + +CREATE TABLE tokens ( + userID INTEGER NOT NULL, + refreshToken TEXT NOT NULL +); \ No newline at end of file diff --git a/pkg/utils/jwt/jwtGenerate.go b/pkg/utils/jwt/jwtGenerate.go new file mode 100644 index 0000000..e69de29 diff --git a/pkg/utils/password/password.go b/pkg/utils/password/password.go new file mode 100644 index 0000000..16cfc8d --- /dev/null +++ b/pkg/utils/password/password.go @@ -0,0 +1,11 @@ +package password + +import "golang.org/x/crypto/bcrypt" + +func HashPassword(password string) (*[]byte, error) { + bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14) + if err != nil { + return nil, err + } + return &bytes, err +} diff --git a/pkg/utils/validator/login.go b/pkg/utils/validator/login.go new file mode 100644 index 0000000..47f2da9 --- /dev/null +++ b/pkg/utils/validator/login.go @@ -0,0 +1 @@ +package validator diff --git a/pkg/utils/validator/password.go b/pkg/utils/validator/password.go new file mode 100644 index 0000000..5ace631 --- /dev/null +++ b/pkg/utils/validator/password.go @@ -0,0 +1,56 @@ +package validator + +import ( + "errors" + "strconv" + "unicode" +) + +type password struct { + minlength int + maxlength int + upSymbol int +} + +func NewValidator(min int, max int, up int) *password { + return &password{ + minlength: min, + maxlength: max, + upSymbol: up, + } +} + +func (p *password) CheckValid(password string) (bool, error) { + var Upper int + if len(password) < p.minlength { + return false, p.errorMinSymbol() + } + if len(password) > p.maxlength { + return false, p.errorMaxSymbol() + } + for _, char := range password { + if unicode.IsUpper(char) { + Upper++ + break + + } + } + + if Upper < p.upSymbol { + return false, p.errorUpperSymbol() + } + return true, nil +} + +func (p *password) errorMinSymbol() error { + + return errors.New("Слижком короткий пароль, минимальное количество : " + strconv.Itoa(p.minlength)) +} +func (p *password) errorMaxSymbol() error { + + return errors.New("Превышен допустимый лимит символов, максимальное количество : " + strconv.Itoa(p.maxlength)) +} +func (p *password) errorUpperSymbol() error { + + return errors.New("В пароле должны быть символ верхнего регистра, количество : " + strconv.Itoa(p.upSymbol)) +}