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
c5f2c84a
Commit
c5f2c84a
authored
2 months ago
by
Ricardo
Browse files
Options
Downloads
Patches
Plain Diff
Issue#12 ADD middleware authenticator
parent
9c4f1ca5
No related branches found
No related tags found
1 merge request
!14
Issue#12 ADD middleware authenticator
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
src/middleware/auth.ts
+31
-0
31 additions, 0 deletions
src/middleware/auth.ts
with
31 additions
and
0 deletions
src/middleware/auth.ts
+
31
−
0
View file @
c5f2c84a
import
{
type
Request
,
type
Response
,
type
NextFunction
}
from
"
express
"
;
import
jwt
,
{
type
JwtPayload
}
from
"
jsonwebtoken
"
;
interface
AuthenticatedRequest
extends
Request
{
user
?:
JwtPayload
|
string
;
}
export
const
tokenAuthenticator
=
async
(
req
:
Request
,
res
:
Response
,
next
:
NextFunction
):
Promise
<
void
>
=>
{
if
(
!
req
.
headers
.
authorization
)
{
res
.
status
(
401
).
json
({
message
:
"
Unauthorized
"
});
return
;
}
const
token
=
req
.
headers
.
authorization
?.
split
(
"
"
)[
1
];
//pega o token do cabecalho da requisicao, undefined se nao achar
if
(
!
token
)
{
res
.
status
(
401
).
json
({
message
:
"
Token Not Found
"
});
return
;
}
try
{
const
decoded
=
jwt
.
verify
(
token
,
process
.
env
[
"
APP_SECRET
"
]
as
string
)
as
JwtPayload
;
//valida o token com app_secret, e atribui como jwtpayload
const
reqAuth
=
req
as
AuthenticatedRequest
;
reqAuth
.
user
=
decoded
;
//req recebe o jwtpayload da validacao
next
();
}
catch
(
error
)
{
res
.
status
(
403
).
json
({
message
:
"
Invalid Token
"
});
}
};
\ No newline at end of file
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