Viacheslav

AuthAPI

Apr 23rd, 2019
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using Microsoft.AspNetCore.Mvc;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using WebChat.Connection;
  7. using WebChat.Models;
  8. using WebChat.Models.ViewModels;
  9. using WebChat.Services;
  10. using WebChat.ViewModels;
  11.  
  12. namespace WebChat.Controllers
  13. {
  14.     [Route("api/[controller]")]
  15.     [ApiController]
  16.     public class AuthController : ControllerBase
  17.     {
  18.         private readonly IAuthService authService;
  19.         private readonly IUserService userService;
  20.  
  21.         public AuthController(IAuthService authService, IUserService userService)
  22.         {
  23.             this.authService = authService ?? throw new ArgumentNullException("Authorization service can not be null, check IoC container");
  24.             this.userService = userService ?? throw new ArgumentNullException("User service can not be null, check IoC container");
  25.         }
  26.        
  27.         [HttpPost("login")]
  28.         public ActionResult<AuthData> Post([FromBody] LoginViewModel model)
  29.         {
  30.             if (!ModelState.IsValid) return BadRequest(ModelState);
  31.  
  32.             var user = userService.GetUserByEmail(model.Email);
  33.  
  34.             if (user == null) return BadRequest(new { email = "no user with this email"});
  35.            
  36.             var passwordValid = authService.VerifyPassword(model.Password, user.Password);
  37.  
  38.             if (!passwordValid) return BadRequest(new { password = "invalid password"});
  39.            
  40.             return authService.GetToken(user.Id);
  41.         }
  42.  
  43.  
  44.         [HttpPost("register")]
  45.         public ActionResult<AuthData> Post([FromBody]RegisterViewModel model)
  46.         {
  47.             if (!ModelState.IsValid) return BadRequest(ModelState);
  48.  
  49.             if (!userService.isEmailUniq(model.Email)) return BadRequest(new { email = "user with this email already exists" });
  50.  
  51.             if (!userService.isUsernameUniq(model.Username)) return BadRequest(new { username = "user with this email already exists" });
  52.  
  53.             var user = userService.CreateUser(model.Username, model.Email, model.Password);
  54.  
  55.             userService.AddUser(user);
  56.  
  57.             return authService.GetToken(user.Id);
  58.         }
  59.        
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment