| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- using BulkPrintingAPI.Configuration;
- using BulkPrintingAPI.Db;
- using BulkPrintingAPI.Services;
- using MAX.Models;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.ModelBinding;
- using Microsoft.Extensions.Logging;
- using System;
- using System.ComponentModel.DataAnnotations;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using System.Threading.Tasks;
- namespace BulkPrintingAPI.Controllers
- {
- //[Produces("application/json")]
- [Route("api/[controller]")]
- public class LoginController : Controller
- {
- public class LoginRequest
- {
- [Required]
- public int? VendorId { get; set; }
- [Required]
- public string SerialNumber { get; set; }
- [Required]
- public int? UserId { get; set; }
- [Required]
- public string Username { get; set; }
- [Required]
- public string Password { get; set; }
- }
- private ILogger logger;
- private TokenAuthenticationOptions tokenAuthenticationOptions;
- private MAXClientFactory clientFactory;
- private MAXDbContext dbContext;
- public LoginController(ILoggerFactory loggerFactory,
- TokenAuthenticationOptions tokenAuthenticationOptions,
- MAXClientFactory clientFactory,
- MAXDbContext dbContext)
- {
- logger = loggerFactory.CreateLogger(GetType().FullName);
- this.tokenAuthenticationOptions = tokenAuthenticationOptions;
- this.clientFactory = clientFactory;
- this.dbContext = dbContext;
- }
- [HttpPost]
- [AllowAnonymous]
- public async Task<IActionResult> Post([FromBody] LoginRequest loginRequest)
- {
- if (! ModelState.IsValid)
- return BadRequest();
- using (var client = clientFactory.GetClient(logger, loginRequest.VendorId.Value,
- loginRequest.SerialNumber, loginRequest.UserId.Value, loginRequest.Username,
- loginRequest.Password))
- {
- User user;
- try
- {
- user = await client.ConnectAsync();
- }
- catch (Exception e)
- {
- logger.LogError(
- "ConnectAsync failed for vendorId={0} serialNumber={1} userId={2} username={3}: {4}",
- loginRequest.VendorId, loginRequest.SerialNumber,
- loginRequest.UserId, loginRequest.Username, e.Message);
- return Unauthorized();
- }
- if (user == null)
- {
- logger.LogInformation(
- "Login failed for vendorId={0} serialNumber={1} userId={2} username={3}",
- loginRequest.VendorId, loginRequest.SerialNumber,
- loginRequest.UserId, loginRequest.Username);
- return Unauthorized();
- }
- try
- {
- await DbHelpers.SyncUserAndVendorWithDb(dbContext, user,
- loginRequest.VendorId.Value,
- loginRequest.SerialNumber);
- }
- catch (Exception e)
- {
- logger.LogError(
- "SyncUserAndVendorWithDb failed for vendorId={0} serialNumber={1} userId={2} username={3}: {4}",
- loginRequest.VendorId, loginRequest.SerialNumber,
- loginRequest.UserId, loginRequest.Username, e.Message);
- return Unauthorized();
- }
- var now = DateTime.UtcNow;
- var encodedJwt = new JwtSecurityTokenHandler().CreateEncodedJwt(
- issuer: tokenAuthenticationOptions.Issuer,
- audience: tokenAuthenticationOptions.Audience,
- subject: new ClaimsIdentity(new Claim[] {
- new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
- new Claim("xpwd", loginRequest.Password),
- new Claim("xvid", loginRequest.VendorId.ToString()),
- new Claim(JwtRegisteredClaimNames.Jti, await tokenAuthenticationOptions.NonceGenerator())
- }),
- notBefore: now,
- expires: now.Add(tokenAuthenticationOptions.Lifetime),
- issuedAt: now,
- signingCredentials: tokenAuthenticationOptions.SigningCredentials,
- encryptingCredentials: tokenAuthenticationOptions.EncryptingCredentials
- );
- return Ok(new {
- access_token = encodedJwt,
- expires_in = (int)tokenAuthenticationOptions.Lifetime.TotalSeconds
- });
- }
- }
- }
- }
|