Commit ec9d81c2 authored by adnansetiawan's avatar adnansetiawan
Browse files

Merge remote-tracking branch 'origin/feature/jwt-auth-on-api' into development

* origin/feature/jwt-auth-on-api:
  clean unnecessary using
  clear some smell code
  implement Api auth based on Role
parents 4a98833e 3ac186d6
Pipeline #24263 passed with stages
in 6 minutes and 36 seconds
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using EasyParking.API.Dtos;
using EasyParking.API.Dtos.Request;
using EasyParking.API.Dtos.Response;
using EasyParking.API.Mapper;
using EasyParking.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace EasyParking.API.Controllers
{
/// <summary>
/// booking api
/// </summary>
[ApiController]
[Route("api/booking")]
[Produces("application/json")]
......@@ -44,8 +40,9 @@ namespace EasyParking.API.Controllers
return new OkObjectResult(response);
}
/// <summary>
/// Get All Booking By Customer
/// Get All Customer
/// </summary>
/// <param name="customerid"></param>
/// <returns></returns>
/// <response code="200">Returns All Booking </response>
[HttpGet("customer/{customerid}")]
......
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using EasyParking.API.Dtos;
using EasyParking.API.Dtos.Request;
using EasyParking.API.Mapper;
using EasyParking.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace EasyParking.API.Controllers
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using EasyParking.API.Dtos;
using EasyParking.API.Dtos.Request;
using EasyParking.API.Mapper;
using EasyParking.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace EasyParking.API.Controllers
{
//
[ApiController]
[Route("api/location")]
[Produces("application/json")]
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using EasyParking.API.Dtos;
using EasyParking.API.Dtos.Request;
using EasyParking.API.Mapper;
using EasyParking.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace EasyParking.API.Controllers
{
......
......@@ -2,20 +2,15 @@
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using EasyParking.API.Dtos;
using EasyParking.API.Dtos.Request;
using EasyParking.API.Mapper;
using EasyParking.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace EasyParking.API.Controllers
......@@ -39,6 +34,7 @@ namespace EasyParking.API.Controllers
/// </summary>
/// <returns></returns>
/// <response code="200">Returns All Users </response>
[Authorize(Roles = "Administrator")]
[HttpGet]
[ProducesResponseType(typeof(UserDetailDto[]), 200)]
public IActionResult Get()
......@@ -181,14 +177,21 @@ namespace EasyParking.API.Controllers
var jwtSecretKey = _configuration.GetSection("Jwt:SecretKey").Value;
// authentication successful so generate jwt token
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, loginRequest.Email)
};
var userExisting = _userService.GetUserByEmail(loginRequest.Email);
if (userExisting != null)
{
claims.Add(new Claim(ClaimTypes.Role, userExisting.UserRole.Name));
}
var subject = new ClaimsIdentity(claims);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(jwtSecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Email, loginRequest.Email)
}),
Subject = subject,
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using EasyParking.API.Dtos;
using EasyParking.API.Dtos.Request;
using EasyParking.API.Mapper;
using EasyParking.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace EasyParking.API.Controllers
{
/// <summary>
/// zona api
/// </summary>
[ApiController]
[Route("api/zona")]
[Produces("application/json")]
......@@ -21,6 +20,12 @@ namespace EasyParking.API.Controllers
private readonly ZonaService _zonaService;
private readonly LocationService _locationService;
private readonly RateService _rateService;
/// <summary>
/// constructor
/// </summary>
/// <param name="zonaRepository"></param>
/// <param name="locationRepository"></param>
/// <param name="rateRepository"></param>
public ZonaController(IZonaRepository zonaRepository, ILocationRepository locationRepository, IRateRepository rateRepository)
{
_zonaService = new ZonaService(zonaRepository);
......
......@@ -29,6 +29,6 @@
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.6.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.3" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using EasyParking.Core;
using EasyParking.Infrastructure.Repositories;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
namespace EasyParking.API
{
public class Startup
......@@ -33,21 +29,6 @@ namespace EasyParking.API
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<EPDbContext>(options => options.UseSqlServer(connectionString));
services.AddScoped<ILocationRepository, LocationRepository>();
services.AddScoped<IZonaRepository, ZonaRepository>();
services.AddScoped<ISlotRepository, SlotRepository>();
services.AddScoped<IUserRoleRepository, UserRoleRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IParkingRepository, ParkingRepository>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IBookingRepository, BookingRepository>();
services.AddScoped<IRateRepository, RateRepository>();
services.AddControllers();
// configure jwt authentication
var jwtSecretKey = Configuration.GetSection("Jwt:SecretKey").Value;
var key = Encoding.ASCII.GetBytes(jwtSecretKey);
......@@ -64,15 +45,59 @@ namespace EasyParking.API
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,
ValidateIssuer = false,
ValidateAudience = false
};
});
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<EPDbContext>(options => options.UseSqlServer(connectionString));
services.AddScoped<ILocationRepository, LocationRepository>();
services.AddScoped<IZonaRepository, ZonaRepository>();
services.AddScoped<ISlotRepository, SlotRepository>();
services.AddScoped<IUserRoleRepository, UserRoleRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IParkingRepository, ParkingRepository>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IBookingRepository, BookingRepository>();
services.AddScoped<IRateRepository, RateRepository>();
services.AddControllers();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("api", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "EasyParking API", Version = "v1" });
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description =
"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";
var commentsFile = Path.Combine(baseDirectory, commentsFileName);
......@@ -99,15 +124,17 @@ namespace EasyParking.API
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
}
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
......
......@@ -10,7 +10,7 @@ namespace EasyParking.Core
void Delete(Guid customerId);
IReadOnlyList<Customer> GetAll();
Customer GetByEmail(string email);
Customer GetByCustomerId(Guid userId);
Customer GetByCustomerId(Guid customerId);
void SetToken(Guid customerId, string token);
void RemoveToken(Guid customerId);
}
......
......@@ -50,6 +50,13 @@ namespace EasyParking.Core
throw new Core.Exceptions.UserNotFoundExeption();
return user;
}
public User GetUserByEmail(string email)
{
var user = _userRepository.GetByEmail(email);
if (user == null)
throw new Core.Exceptions.UserNotFoundExeption();
return user;
}
public User Update(User user)
{
_userRepository.Update(user);
......
......@@ -14,9 +14,9 @@ namespace EasyParking.Infrastructure.Repositories
_dbContext = dbContext;
}
public void Delete(Guid Id)
public void Delete(Guid customerId)
{
var existingCustomer = GetExistingCustomer(Id);
var existingCustomer = GetExistingCustomer(customerId);
if (existingCustomer != null)
{
_dbContext.Customers.Remove(existingCustomer);
......@@ -34,38 +34,38 @@ namespace EasyParking.Infrastructure.Repositories
var result = _dbContext.Customers.FirstOrDefault(x => x.Id == Id);
return result;
}
public Core.Customer GetByCustomerId(Guid Id)
public Core.Customer GetByCustomerId(Guid customerId)
{
var result = GetExistingCustomer(Id);
var result = GetExistingCustomer(customerId);
if (result == null)
return null;
return result.MapToEntity();
}
public void Insert(Core.Customer data)
public void Insert(Core.Customer customer)
{
_dbContext.Customers.Add(new Customer
{
Id = data.Id,
Name = data.Name,
Email = data.Email,
PhoneNumber = data.PhoneNumber,
Address = data.Address,
HashedPassword = data.HashedPassword,
CreatedDate = data.CreatedDate
Id = customer.Id,
Name = customer.Name,
Email = customer.Email,
PhoneNumber = customer.PhoneNumber,
Address = customer.Address,
HashedPassword = customer.HashedPassword,
CreatedDate = customer.CreatedDate
});
_dbContext.SaveChanges();
}
public void Update(Core.Customer data)
public void Update(Core.Customer customer)
{
var existingData = GetExistingCustomer(data.Id);
var existingData = GetExistingCustomer(customer.Id);
if (existingData != null)
{
existingData.ModifiedDate = data.ModifiedDate;
existingData.Name = data.Name;
existingData.PhoneNumber = data.PhoneNumber;
existingData.Address = data.Address;
existingData.ModifiedDate = customer.ModifiedDate;
existingData.Name = customer.Name;
existingData.PhoneNumber = customer.PhoneNumber;
existingData.Address = customer.Address;
_dbContext.Customers.Update(existingData);
_dbContext.SaveChanges();
}
......
......@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq;
using EasyParking.Core;
using EasyParking.Infrastructure.Mapper;
using EasyParking.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
namespace EasyParking.Infrastructure.Repositories
......@@ -16,9 +15,9 @@ namespace EasyParking.Infrastructure.Repositories
_dbContext = dbContext;
}
public void Delete(Guid Id)
public void Delete(Guid userId)
{
var existingUser = GetExistingUser(Id);
var existingUser = GetExistingUser(userId);
if (existingUser != null)
{
_dbContext.Users.Remove(existingUser);
......@@ -36,36 +35,36 @@ namespace EasyParking.Infrastructure.Repositories
var result = _dbContext.Users.Include(z => z.UserRole).FirstOrDefault(x => x.Id == Id);
return result;
}
public Core.User GetByUserId(Guid Id)
public Core.User GetByUserId(Guid userId)
{
var result = GetExistingUser(Id);
var result = GetExistingUser(userId);
if (result == null)
return null;
return result.MapToEntity();
}
public void Insert(Core.User data)
public void Insert(Core.User user)
{
_dbContext.Users.Add(new User
{
Id = data.Id,
Name = data.Name,
Email = data.Email,
HashedPassword = data.HashedPassword,
CreatedDate = data.CreatedDate,
UserRoleId = data.UserRole.Id
Id = user.Id,
Name = user.Name,
Email = user.Email,
HashedPassword = user.HashedPassword,
CreatedDate = user.CreatedDate,
UserRoleId = user.UserRole.Id
});
_dbContext.SaveChanges();
}
public void Update(Core.User data)
public void Update(Core.User user)
{
var existingData = GetExistingUser(data.Id);
var existingData = GetExistingUser(user.Id);
if (existingData != null)
{
existingData.ModifiedDate = data.ModifiedDate;
existingData.Name = data.Name;
existingData.UserRoleId = data.UserRole.Id;
existingData.ModifiedDate = user.ModifiedDate;
existingData.Name = user.Name;
existingData.UserRoleId = user.UserRole.Id;
_dbContext.Users.Update(existingData);
_dbContext.SaveChanges();
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment