Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
T
treinamento-2025.1-backend
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Harbor Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
RICARDO PRADO FARIA
treinamento-2025.1-backend
Commits
9a70e4e9
Commit
9a70e4e9
authored
2 months ago
by
Amanda Pollyanna da Silva Rodrigues
Browse files
Options
Downloads
Patches
Plain Diff
Issue
#11
ADD login user route
parent
07a36a68
No related branches found
No related tags found
1 merge request
!12
Issue #11 ADD login user route
Changes
3
Show whitespace changes
Inline
Side-by-side
Showing
3 changed files
src/handlers/user.ts
+95
-50
95 additions, 50 deletions
src/handlers/user.ts
src/index.ts
+4
-3
4 additions, 3 deletions
src/index.ts
src/validators/userValidator.ts
+11
-12
11 additions, 12 deletions
src/validators/userValidator.ts
with
110 additions
and
65 deletions
src/handlers/user.ts
+
95
−
50
View file @
9a70e4e9
...
@@ -4,7 +4,7 @@ import { db } from "@/db";
...
@@ -4,7 +4,7 @@ import { db } from "@/db";
import
{
or
,
eq
}
from
'
drizzle-orm
'
;
import
{
or
,
eq
}
from
'
drizzle-orm
'
;
import
{
usersTable
}
from
"
@/db/schema
"
;
import
{
usersTable
}
from
"
@/db/schema
"
;
import
bcrypt
from
"
bcrypt
"
;
import
bcrypt
from
"
bcrypt
"
;
import
{
z
}
from
'
zod
'
;
import
jwt
from
'
jsonwebtoken
'
;
export
default
class
User
{
export
default
class
User
{
static
userRequestValidation
(
req
:
Request
){
//valida a requisição do usuário
static
userRequestValidation
(
req
:
Request
){
//valida a requisição do usuário
...
@@ -76,17 +76,16 @@ export default class User{
...
@@ -76,17 +76,16 @@ export default class User{
return
res
.
status
(
408
).
json
({
error
:
"
Error during user deletion
"
});
return
res
.
status
(
408
).
json
({
error
:
"
Error during user deletion
"
});
}
}
}
}
}
static
createUser
=
async
(
req
:
Request
,
res
:
Response
)
=>
{
export
const
createUser
=
async
(
req
:
Request
,
res
:
Response
)
=>
{
try
{
try
{
// validar com o Zod
const
parsedData
=
userSchema
.
safeParse
(
req
.
body
);
const
parsedData
=
userSchema
.
safeParse
(
req
.
body
);
if
(
!
parsedData
.
success
)
{
if
(
!
parsedData
.
success
)
{
return
res
.
status
(
400
).
json
({
error
:
"
Dados Inválidos
"
,
details
:
parsedData
.
error
.
errors
});
return
res
.
status
(
400
).
json
({
error
:
"
Dados Inválidos
"
,
details
:
parsedData
.
error
.
errors
});
}
}
// desestruturação dos dados para inserir no banco
const
{
name
,
email
,
password
,
birthday
,
cpf
,
money
,
cyberpsychosis
,
cyberLimit
}
=
parsedData
.
data
;
const
{
name
,
email
,
password
,
birthday
,
cpf
,
money
,
cyberpsychosis
,
cyberLimit
}
=
parsedData
.
data
;
const
hashedPassword
=
await
bcrypt
.
hash
(
password
,
10
);
const
hashedPassword
=
await
bcrypt
.
hash
(
password
,
10
);
...
@@ -106,31 +105,77 @@ export const createUser = async (req: Request, res: Response) => {
...
@@ -106,31 +105,77 @@ export const createUser = async (req: Request, res: Response) => {
}
catch
(
error
)
{
}
catch
(
error
)
{
console
.
error
(
error
);
console
.
error
(
error
);
return
res
.
status
(
500
).
json
({
error
:
"
Erro ao inserir o usuário. Por favor, tente novamente mais tarde.
"
});
return
res
.
status
(
500
).
json
({
error
:
"
Erro ao inserir o usuário.
"
});
}
}
}
};
export
const
readUser
=
async
(
req
:
Request
,
res
:
Response
)
=>
{
static
readUser
=
async
(
req
:
Request
,
res
:
Response
)
=>
{
try
{
try
{
const
{
id
,
nome
}
=
req
.
params
;
//extracao da requisicao
// extrair id e nome da requisição
const
{
id
,
name
}
=
req
.
params
;
const
parsedData
=
userSchema
.
safeParse
({
id
,
nome
});
// converter id para número
const
parsedId
=
parseInt
(
id
,
10
);
if
(
isNaN
(
parsedId
))
{
return
res
.
status
(
400
).
json
({
error
:
"
ID inválido
"
});
}
// validar com o Zod
const
parsedData
=
userSchema
.
safeParse
({
id
:
parsedId
,
name
});
if
(
!
parsedData
.
success
)
{
if
(
!
parsedData
.
success
)
{
return
res
.
status
(
400
).
json
({
error
:
"
Dados Inválidos
"
,
details
:
parsedData
.
error
.
errors
});}
return
res
.
status
(
400
).
json
({
error
:
"
Dados Inválidos
"
,
details
:
parsedData
.
error
.
errors
});
}
const
result
=
await
db
.
select
().
from
(
usersTable
).
where
(
or
(
eq
(
usersTable
.
id
,
id
),
eq
(
usersTable
.
nome
,
nome
))).
limit
(
1
);
const
result
=
await
db
.
select
().
from
(
usersTable
)
.
where
(
or
(
eq
(
usersTable
.
id
,
parsedId
),
eq
(
usersTable
.
name
,
name
)))
.
limit
(
1
);
if
(
result
.
length
===
0
)
{
// array vazio
if
(
result
.
length
===
0
)
{
// array vazio
return
res
.
status
(
404
).
json
({
error
:
"
Usuário não encontrado
"
});
return
res
.
status
(
404
).
json
({
error
:
"
Usuário não encontrado
"
});
}
}
delete
result
[
0
].
password
;
// desestruturar result e remover password
const
{
password
,
...
userWithoutPassword
}
=
result
[
0
];
return
res
.
status
(
200
).
json
(
userWithoutPassword
);
return
res
.
status
(
200
).
json
(
result
[
0
]);
}
catch
(
error
)
{
}
catch
(
error
)
{
console
.
error
(
error
);
console
.
error
(
error
);
return
res
.
status
(
500
).
json
({
error
:
"
Erro ao buscar o usuário. Por favor, tente novamente mais tarde.
"
});
return
res
.
status
(
500
).
json
({
error
:
"
Erro ao buscar o usuário.
"
});
}
}
static
loginUser
=
async
(
req
:
Request
,
res
:
Response
)
=>
{
try
{
const
{
email
,
password
}
=
req
.
body
;
// buscar usuário
const
user
=
await
db
.
select
().
from
(
usersTable
).
where
(
eq
(
usersTable
.
email
,
email
)).
limit
(
1
);
if
(
user
.
length
===
0
)
{
// array vazio
return
res
.
status
(
404
).
json
({
message
:
'
Usuário não encontrado
'
});
}
// validar senha
const
isPasswordValid
=
await
bcrypt
.
compare
(
password
,
user
[
0
].
password
);
if
(
!
isPasswordValid
)
{
return
res
.
status
(
401
).
json
({
message
:
'
Senha incorreta
'
});
}
// criar chave secreta para assinar e validar tokens, guardar no .env
const
jwtSecret
=
process
.
env
[
"
JWT_SECRET
"
];
if
(
!
jwtSecret
)
{
return
res
.
status
(
500
).
json
({
error
:
"
Chave secreta do JWT não configurada
"
});
}
//gerar token
const
token
=
jwt
.
sign
({
id
:
user
[
0
].
id
,
email
:
user
[
0
].
email
},
jwtSecret
,
{
expiresIn
:
'
1h
'
});
return
res
.
status
(
200
).
json
({
message
:
'
Login bem-sucedido
'
,
token
});
}
catch
(
error
)
{
console
.
error
(
error
);
return
res
.
status
(
500
).
json
({
error
:
"
Erro ao realizar login
"
});
}
}
}
}
}
This diff is collapsed.
Click to expand it.
src/index.ts
+
4
−
3
View file @
9a70e4e9
import
express
,
{
urlencoded
,
json
}
from
'
express
'
import
express
,
{
urlencoded
,
json
}
from
'
express
'
import
dotenv
from
'
dotenv
'
import
dotenv
from
'
dotenv
'
import
{
createUser
,
readUser
}
from
'
./handlers/user
'
;
import
User
from
'
./handlers/user
'
;
import
Implant
from
'
@/handlers/implants
'
import
Implant
from
'
@/handlers/implants
'
import
{
Auth
}
from
'
@/middleware/auth
'
import
{
Auth
}
from
'
@/middleware/auth
'
...
@@ -14,8 +14,9 @@ app.use(urlencoded({ extended: true }))
...
@@ -14,8 +14,9 @@ app.use(urlencoded({ extended: true }))
app
.
use
(
json
())
app
.
use
(
json
())
// Rotas de usuário
// Rotas de usuário
app
.
post
(
'
/addUser
'
,
createUser
)
app
.
post
(
'
/addUser
'
,
User
.
createUser
)
app
.
get
(
'
/getUser
'
,
readUser
)
app
.
get
(
'
/getUser
'
,
User
.
readUser
)
app
.
post
(
'
/loginUser
'
,
User
.
loginUser
)
// Definir a porta e iniciar o servidor
// Definir a porta e iniciar o servidor
const
PORT
=
process
.
env
[
'
PORT
'
]
||
3000
const
PORT
=
process
.
env
[
'
PORT
'
]
||
3000
...
...
This diff is collapsed.
Click to expand it.
src/validators/userValidator.ts
+
11
−
12
View file @
9a70e4e9
...
@@ -12,4 +12,3 @@ export const userSchema = z.object({
...
@@ -12,4 +12,3 @@ export const userSchema = z.object({
cyberpsychosis
:
z
.
number
(),
// a definir restrições de validação
cyberpsychosis
:
z
.
number
(),
// a definir restrições de validação
cyberLimit
:
z
.
number
(),
cyberLimit
:
z
.
number
(),
});
});
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment