add register user

main
Shuhrat Tulyaganov 2023-04-14 17:35:25 +03:00
parent 7dfe981b53
commit 3026f89f2e
16 changed files with 275 additions and 67 deletions

7
go.mod
View File

@ -5,6 +5,7 @@ go 1.19
require github.com/sirupsen/logrus v1.9.0 require github.com/sirupsen/logrus v1.9.0
require ( 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/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.14.0 // indirect github.com/jackc/pgconn v1.14.0 // indirect
github.com/jackc/pgio v1.0.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/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.1 // indirect github.com/stretchr/testify v1.8.1 // indirect
golang.org/x/crypto v0.6.0 // indirect golang.org/x/crypto v0.8.0 // indirect
golang.org/x/sys v0.5.0 // indirect golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.7.0 // indirect golang.org/x/text v0.9.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

8
go.sum
View File

@ -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-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/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/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/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 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= 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.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 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= 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/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.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= 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.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 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 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-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-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 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.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 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 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-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-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=

View File

@ -92,7 +92,7 @@ func (f *Filmsrepo) FindById(id string) (*model.Films, error) {
func (f *Filmsrepo) FindByName(name string) (*[]model.Films, error) { func (f *Filmsrepo) FindByName(name string) (*[]model.Films, error) {
var films []model.Films 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 { if err != nil {
return nil, err return nil, err
} }
@ -100,10 +100,7 @@ func (f *Filmsrepo) FindByName(name string) (*[]model.Films, error) {
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
var film model.Films var film model.Films
err = rows.Scan(&film.Id, &film.Ru_title, &film.Orig_title, &film.Imdb_id, &film.Kinopoisk_id, err = rows.Scan(&film.Id, &film.Ru_title, &film.Year, &film.PosterUrl, &film.Contenttype)
&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)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -2,10 +2,9 @@ package model
type User struct { type User struct {
Id int Id int
Login string Login string `json:"login"`
Email string Email string `json:"email"`
Password string Password string `json:"password"`
Avatar_Url string Avatar_Url string
Token string
PermisionLVL int PermisionLVL int
} }

View File

@ -125,17 +125,14 @@ func (s *Siriesrepo) FindByAll() (*[]model.Siries, error) {
func (s *Siriesrepo) FindByName(name string) (*[]model.Siries, error) { func (s *Siriesrepo) FindByName(name string) (*[]model.Siries, error) {
var buffs []model.Siries 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 { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
var buff model.Siries var buff model.Siries
err = rows.Scan(&buff.Id, &buff.Ru_title, &buff.Orig_title, &buff.Imdb_id, &buff.Kinopoisk_id, err = rows.Scan(&buff.Id, &buff.Ru_title, &buff.Year, &buff.PosterUrl, &buff.Contenttype)
&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)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -11,27 +11,55 @@ type Userrepo struct {
db Bd db Bd
} }
func (u *Userrepo) Create(user *model.User) (*model.User, error) { func (u *Userrepo) Create(user *model.User) error {
err := u.db.db.QueryRow(context.Background(), _, err := u.db.db.Exec(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). "INSERT INTO users (login, email, password, permisionlvl) VALUES($1, $2, $3, $4)", user.Login, user.Email, user.Password, user.PermisionLVL)
Scan(&user.Id, &user.PermisionLVL)
if err != nil { if err != nil {
return nil, err return err
} }
return user, nil return nil
} }
func (u *Userrepo) FindById(id string) (*model.User, error) { func (u *Userrepo) FindById(id string) (*model.User, error) {
var user model.User var user model.User
query := fmt.Sprintf("SELECT * FROM users WHERE Id = %s;", id) query := fmt.Sprintf("SELECT * FROM users WHERE Id = %s;", id)
err := u.db.db.QueryRow(context.Background(), query). 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 { if err != nil {
return nil, err return nil, err
} }
return &user, nil 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) { func (u *Userrepo) FindByAll() (*model.User, error) {
return nil, nil return nil, nil
} }

View File

@ -31,6 +31,8 @@ func (r *RestServer) HandleHello() http.HandlerFunc {
} }
w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type") 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)) io.WriteString(w, strconv.Itoa(*cout))
} }
} }
@ -62,21 +64,33 @@ func (r *RestServer) HendleFindAll() http.HandlerFunc {
func (r *RestServer) HeandleFilmsFindName() http.HandlerFunc { func (r *RestServer) HeandleFilmsFindName() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] name := mux.Vars(res)["name"]
films, err := r.db.Films().FindByName(name) films, err := r.db.Films().FindByName(name)
if err != nil { if err != nil {
r.logger.Errorln(err) r.logger.Errorln(err)
} }
if *films != nil {
jsonData, err := json.Marshal(films) jsonData, err := json.Marshal(films)
if err != nil { if err != nil {
r.logger.Errorln(err) r.logger.Errorln(err)
} }
io.WriteString(w, string(jsonData)) io.WriteString(w, string(jsonData))
} else {
io.WriteString(w, string(`[]`))
}
} }
} }
func (r *RestServer) HeandleFilmsSortGenres() http.HandlerFunc { func (r *RestServer) HeandleFilmsSortGenres() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] name := mux.Vars(res)["name"]
films, err := r.db.Films().SortByGanres(name) films, err := r.db.Films().SortByGanres(name)
if err != nil { if err != nil {
@ -92,6 +106,9 @@ func (r *RestServer) HeandleFilmsSortGenres() http.HandlerFunc {
func (r *RestServer) HendleFindID() http.HandlerFunc { func (r *RestServer) HendleFindID() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] id := mux.Vars(res)["id"]
fmt.Println(mux.Vars(res)) fmt.Println(mux.Vars(res))
film, err := r.db.Films().FindById(id) film, err := r.db.Films().FindById(id)
@ -102,14 +119,16 @@ func (r *RestServer) HendleFindID() http.HandlerFunc {
if err != nil { if err != nil {
r.logger.Errorln(err) 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)) io.WriteString(w, string(jsonData))
} }
} }
func (r *RestServer) HendlePagination() http.HandlerFunc { func (r *RestServer) HendlePagination() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] id := mux.Vars(res)["page"]
films, err := r.db.Films().Pagination(id) films, err := r.db.Films().Pagination(id)
if err != nil { if err != nil {
@ -119,8 +138,6 @@ func (r *RestServer) HendlePagination() http.HandlerFunc {
if err != nil { if err != nil {
r.logger.Errorln(err) 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)) io.WriteString(w, string(jsondata))
} }
@ -128,6 +145,9 @@ func (r *RestServer) HendlePagination() http.HandlerFunc {
func (r *RestServer) HeadleGetLastItem() http.HandlerFunc { func (r *RestServer) HeadleGetLastItem() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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() films, err := r.db.Films().LastItem()
if err != nil { if err != nil {
r.logger.Errorln(err) r.logger.Errorln(err)
@ -136,8 +156,6 @@ func (r *RestServer) HeadleGetLastItem() http.HandlerFunc {
if err != nil { if err != nil {
r.logger.Errorln(err) 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)) io.WriteString(w, string(jsondata))
} }
} }

View File

@ -8,6 +8,13 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
const (
ContextKeyUser = iota
defaultPermLvl = 1
writerPermLvl = 2
adminPermLvl = 3
)
type RestServer struct { type RestServer struct {
config *Config config *Config
logger *logrus.Logger logger *logrus.Logger

View File

@ -23,14 +23,15 @@ func (r *RestServer) configureRouterSiries() {
func (r *RestServer) HandleHelloSiries() http.HandlerFunc { func (r *RestServer) HandleHelloSiries() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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") id := res.URL.Query().Get("id")
fmt.Println(id) fmt.Println(id)
cout, err := r.db.Siries().GetCountFilms() cout, err := r.db.Siries().GetCountFilms()
if err != nil { if err != nil {
r.logger.Errorln(err) 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)) io.WriteString(w, strconv.Itoa(*cout))
} }
} }
@ -62,21 +63,32 @@ func (r *RestServer) HendleFindAllSiries() http.HandlerFunc {
func (r *RestServer) HeandleSiriesFindName() http.HandlerFunc { func (r *RestServer) HeandleSiriesFindName() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] name := mux.Vars(res)["name"]
siries, err := r.db.Siries().FindByName(name) siries, err := r.db.Siries().FindByName(name)
if err != nil { if err != nil {
r.logger.Errorln(err) r.logger.Errorln(err)
} }
if *siries != nil {
jsonData, err := json.Marshal(siries) jsonData, err := json.Marshal(siries)
if err != nil { if err != nil {
r.logger.Errorln(err) r.logger.Errorln(err)
} }
io.WriteString(w, string(jsonData)) io.WriteString(w, string(jsonData))
} else {
io.WriteString(w, string(`[]`))
}
} }
} }
func (r *RestServer) HeandleSiriesSortGenres() http.HandlerFunc { func (r *RestServer) HeandleSiriesSortGenres() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] name := mux.Vars(res)["name"]
siries, err := r.db.Siries().SortByGanres(name) siries, err := r.db.Siries().SortByGanres(name)
if err != nil { if err != nil {
@ -92,6 +104,9 @@ func (r *RestServer) HeandleSiriesSortGenres() http.HandlerFunc {
func (r *RestServer) HendleFindIDSiries() http.HandlerFunc { func (r *RestServer) HendleFindIDSiries() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] id := mux.Vars(res)["id"]
fmt.Println(mux.Vars(res)) fmt.Println(mux.Vars(res))
siries, err := r.db.Siries().FindById(id) siries, err := r.db.Siries().FindById(id)
@ -102,14 +117,15 @@ func (r *RestServer) HendleFindIDSiries() http.HandlerFunc {
if err != nil { if err != nil {
r.logger.Errorln(err) 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)) io.WriteString(w, string(jsonData))
} }
} }
func (r *RestServer) HendlePaginationSiries() http.HandlerFunc { func (r *RestServer) HendlePaginationSiries() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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"] id := mux.Vars(res)["page"]
siries, err := r.db.Siries().Pagination(id) siries, err := r.db.Siries().Pagination(id)
if err != nil { if err != nil {
@ -119,8 +135,6 @@ func (r *RestServer) HendlePaginationSiries() http.HandlerFunc {
if err != nil { if err != nil {
r.logger.Errorln(err) 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)) io.WriteString(w, string(jsondata))
} }
@ -128,6 +142,9 @@ func (r *RestServer) HendlePaginationSiries() http.HandlerFunc {
func (r *RestServer) HeadleGetLastItemSiries() http.HandlerFunc { func (r *RestServer) HeadleGetLastItemSiries() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { 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() siries, err := r.db.Siries().LastItem()
if err != nil { if err != nil {
r.logger.Errorln(err) r.logger.Errorln(err)
@ -136,8 +153,6 @@ func (r *RestServer) HeadleGetLastItemSiries() http.HandlerFunc {
if err != nil { if err != nil {
r.logger.Errorln(err) 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)) io.WriteString(w, string(jsondata))
} }
} }

View File

@ -1,36 +1,49 @@
package restserver package restserver
import ( import (
"fmt"
"io"
"net/http" "net/http"
"git.ukamnya.ru/stulyaganov/RestApiv2/internal/bd/model" "git.ukamnya.ru/stulyaganov/RestApiv2/internal/bd/model"
"git.ukamnya.ru/stulyaganov/RestApiv2/pkg/utils/password"
) )
func (r *RestServer) configureRouterUser() { 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 { func (r *RestServer) HandleFuncRegUser() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) { return func(w http.ResponseWriter, res *http.Request) {
user := model.User{} users := res.Context().Value(ContextKeyUser).(*model.User)
err := res.ParseForm()
hash, err := password.HashPassword(users.Password)
if err != nil { if err != nil {
r.logger.Error(err) r.logger.Error(err)
} }
user.Id = 1 users.Password = string(*hash)
user.Login = res.Form.Get("user") err = r.db.User().Create(users)
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)
if err != nil { if err != nil {
r.logger.Errorln(err) r.logger.Error(err)
} } else {
if RetUser != nil { io.WriteString(w, `{"data":"Пользователь создан"}`)
r.logger.Infoln("Create new user with id = ", RetUser.Id, " and with permissionLvl = ", RetUser.Id)
}
} }
} }
}
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")
}
}

View File

@ -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)))
}
}

View File

@ -22,12 +22,20 @@ CREATE TABLE films (
); );
CREATE TABLE users ( CREATE TABLE users (
id INTEGER NOT NULL, id SERIAL,
login VARCHAR(25) not NULL, login TEXT not NULL,
email VARCHAR(255) NOT NULL, email TEXT NOT NULL,
password VARCHAR(2500) NOT NULL, password TEXT NOT NULL,
avatar_url VARCHAR(2500), avatar_url TEXT,
token VARCHAR(2500) NOT NULL,
permisionLVL INTEGER NOT NULL, permisionLVL INTEGER NOT NULL,
SaveItem INTEGER Array,
LaterItem INTEGER Array,
WantItem INTEGER Array,
PRIMARY KEY(id) PRIMARY KEY(id)
); );
CREATE TABLE tokens (
userID INTEGER NOT NULL,
refreshToken TEXT NOT NULL
);

View File

View File

@ -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
}

View File

@ -0,0 +1 @@
package validator

View File

@ -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))
}