1 | package mk.ukim.finki.busngobackend.config
|
---|
2 |
|
---|
3 | import io.jsonwebtoken.Claims
|
---|
4 | import io.jsonwebtoken.Jwts
|
---|
5 | import io.jsonwebtoken.security.Keys
|
---|
6 | import org.springframework.security.core.userdetails.UserDetails
|
---|
7 | import org.springframework.stereotype.Service
|
---|
8 | import java.security.Key
|
---|
9 | import java.util.Date
|
---|
10 |
|
---|
11 | @Service
|
---|
12 | class JwtService {
|
---|
13 | private val secretKey =
|
---|
14 | Keys.hmacShaKeyFor(
|
---|
15 | "hu55nfa3pRrBRV4DIlvKVDMrg7jnqla9".toByteArray(),
|
---|
16 | )
|
---|
17 |
|
---|
18 | fun extractUsername(token: String): String? = extractClaim(token, Claims::getSubject)
|
---|
19 |
|
---|
20 | fun <T> extractClaim(
|
---|
21 | token: String,
|
---|
22 | claimsResolver: (Claims) -> T,
|
---|
23 | ): T {
|
---|
24 | val claims = extractAllClaims(token)
|
---|
25 | return claimsResolver(claims)
|
---|
26 | }
|
---|
27 |
|
---|
28 | fun generateToken(
|
---|
29 | extraClaims: Map<String, Any> = emptyMap(),
|
---|
30 | userDetails: UserDetails,
|
---|
31 | ): String =
|
---|
32 | Jwts
|
---|
33 | .builder()
|
---|
34 | .claims()
|
---|
35 | .subject(userDetails.username)
|
---|
36 | .issuedAt(Date(System.currentTimeMillis()))
|
---|
37 | .expiration(Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
|
---|
38 | .add(extraClaims)
|
---|
39 | .and()
|
---|
40 | .signWith(getSignInKey())
|
---|
41 | .compact()
|
---|
42 |
|
---|
43 | fun isTokenValid(
|
---|
44 | token: String,
|
---|
45 | userDetails: UserDetails,
|
---|
46 | ): Boolean {
|
---|
47 | val username = extractUsername(token)
|
---|
48 | return username == userDetails.username && !isTokenExpired(token)
|
---|
49 | }
|
---|
50 |
|
---|
51 | private fun isTokenExpired(token: String): Boolean = extractExpiration(token).before(Date())
|
---|
52 |
|
---|
53 | private fun extractExpiration(token: String): Date = extractClaim(token, Claims::getExpiration)
|
---|
54 |
|
---|
55 | private fun extractAllClaims(token: String): Claims =
|
---|
56 | Jwts
|
---|
57 | .parser()
|
---|
58 | .verifyWith(secretKey)
|
---|
59 | .build()
|
---|
60 | .parseSignedClaims(token)
|
---|
61 | .payload
|
---|
62 |
|
---|
63 | private fun getSignInKey(): Key = secretKey
|
---|
64 | }
|
---|