Repository navigation
Expand file tree
/
Copy pathTokenWebController.cs
More file actions
188 lines (167 loc) · 6.93 KB
/
Copy pathTokenWebController.cs
File metadata and controls
188 lines (167 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using Grand.Module.Api.Commands.Models.Common;
using Grand.Module.Api.DTOs;
using Grand.Module.Api.Models.Common;
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Mediator;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
namespace Grand.Module.Api.Controllers;
[ApiExplorerSettings(GroupName = "v2")]
[ApiController]
[Route("[controller]/[action]")]
[Tags("Create token")]
public class TokenWebController : ControllerBase
{
private readonly IAntiforgery _antiforgery;
private readonly FrontendAPIConfig _apiConfig;
private readonly ICustomerService _customerService;
private readonly IMediator _mediator;
private readonly IRefreshTokenService _refreshTokenService;
private readonly IExternalSignInPolicy _externalSignInPolicy;
private readonly IContextAccessor _contextAccessor;
public TokenWebController(
ICustomerService customerService,
IMediator mediator,
IContextAccessor contextAccessor,
IRefreshTokenService refreshTokenService,
IExternalSignInPolicy externalSignInPolicy,
IAntiforgery antiforgery,
FrontendAPIConfig apiConfig)
{
_customerService = customerService;
_mediator = mediator;
_contextAccessor = contextAccessor;
_refreshTokenService = refreshTokenService;
_externalSignInPolicy = externalSignInPolicy;
_antiforgery = antiforgery;
_apiConfig = apiConfig;
}
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[HttpPost]
public async Task<IActionResult> Guest()
{
if (!_apiConfig.Enabled)
return BadRequest("API is disabled");
var customer = new Customer {
CustomerGuid = Guid.NewGuid(),
Active = true,
StoreId = _contextAccessor.StoreContext.CurrentStore.Id,
LastActivityDateUtc = DateTime.UtcNow
};
customer = await _customerService.InsertGuestCustomer(customer);
var claims = new Dictionary<string, string> {
{ "Guid", customer.CustomerGuid.ToString() }
};
var tokenDto = await GetToken(claims, customer);
return Ok(tokenDto);
}
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[HttpPost]
public async Task<IActionResult> Login([FromBody] LoginWebModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
try
{
var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id);
var claims = new Dictionary<string, string> {
{ "CustomerId", customer.Id },
{ "Email", model.Email },
{ "Token", customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken) }
};
var tokenDto = await GetToken(claims, customer);
return Ok(tokenDto);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[HttpPost]
public async Task<IActionResult> Refresh([FromBody] TokenDto tokenDto)
{
if (!_apiConfig.Enabled)
return BadRequest("API is disabled");
Customer customer = null;
var claims = new Dictionary<string, string>();
ClaimsPrincipal principal;
string customerId;
string email;
string guid;
try
{
principal = _refreshTokenService.GetPrincipalFromToken(tokenDto.AccessToken);
customerId = principal.Claims.FirstOrDefault(x => x.Type == "CustomerId")?.Value;
email = principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value;
guid = principal.Claims.FirstOrDefault(x => x.Type == "Guid")?.Value;
}
catch (Exception)
{
return BadRequest("Invalid access token");
}
//prefer the stable customer id (unambiguous with per-store identity); fall back to e-mail/guid for
//tokens issued before the id claim existed
if (!string.IsNullOrEmpty(customerId))
customer = await _customerService.GetCustomerById(customerId);
else if (!string.IsNullOrEmpty(email))
customer = await _customerService.GetCustomerByEmail(email);
else if (!string.IsNullOrEmpty(guid))
customer = await _customerService.GetCustomerByGuid(Guid.Parse(guid));
if (customer == null)
return BadRequest("Invalid access token");
//tokens obtained with the password before the account had to sign in through the provider are not renewed:
//the provider could not stop them for a user it disabled. Guests never had a password: their tokens stay
if (!string.IsNullOrEmpty(customer.Email) &&
!(await _externalSignInPolicy.PasswordSignIn(customer, SignInSurface.FrontendApi)).Allowed)
return BadRequest("Invalid refresh token");
//rebuild the claims from the resolved customer (registered carry id/email/token, guests carry the guid)
if (!string.IsNullOrEmpty(customer.Email))
{
claims.Add("CustomerId", customer.Id);
claims.Add("Email", customer.Email);
claims.Add("Token", customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken));
}
else
{
claims.Add("Guid", customer.CustomerGuid.ToString());
}
var customerRefreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);
if (customerRefreshToken is null || !customerRefreshToken.Token.Equals(tokenDto.RefreshToken))
return BadRequest("Invalid refresh token");
if (customerRefreshToken.ValidTo.CompareTo(DateTime.UtcNow) < 0) return BadRequest("Token expired");
var token = await GetToken(claims, customer);
return Ok(token);
}
[HttpGet]
[AllowAnonymous]
public IActionResult Antiforgery()
{
if (!_apiConfig.Enabled)
return BadRequest("API is disabled");
var token = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken;
return Ok(token);
}
private async Task<TokenDto> GetToken(Dictionary<string, string> claims, Customer customer)
{
var refreshTokenValue = _refreshTokenService.GenerateRefreshToken();
var refreshToken = await _refreshTokenService.SaveRefreshTokenToCustomer(customer, refreshTokenValue);
claims.Add("RefreshId", refreshToken.RefreshId);
var token = await _mediator.Send(new GenerateTokenWebCommand { Claims = claims });
return new TokenDto {
AccessToken = token,
RefreshToken = refreshTokenValue
};
}
}