Skip to content

Commit

Permalink
Merge pull request EasyMicroservices#11 from MahdiyarGHD/develop
Browse files Browse the repository at this point in the history
Add RegenerateToken & update client
  • Loading branch information
Ali-YousefiTelori authored Aug 17, 2023
2 parents 0f9fb6c + 5ff7ad3 commit a980373
Show file tree
Hide file tree
Showing 6 changed files with 247 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,84 @@ public virtual async System.Threading.Tasks.Task<UserResponseContractMessageCont
}
}

/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual System.Threading.Tasks.Task<UserResponseContractMessageContract> RegenerateTokenAsync(RegenerateTokenContract body)
{
return RegenerateTokenAsync(body, System.Threading.CancellationToken.None);
}

/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual async System.Threading.Tasks.Task<UserResponseContractMessageContract> RegenerateTokenAsync(RegenerateTokenContract body, System.Threading.CancellationToken cancellationToken)
{
var urlBuilder_ = new System.Text.StringBuilder();
urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Users/RegenerateToken");

var client_ = _httpClient;
var disposeClient_ = false;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value);
var content_ = new System.Net.Http.StringContent(json_);
content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
request_.Content = content_;
request_.Method = new System.Net.Http.HttpMethod("POST");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain"));

PrepareRequest(client_, request_, urlBuilder_);

var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

PrepareRequest(client_, request_, url_);

var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var disposeResponse_ = true;
try
{
var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}

ProcessResponse(client_, response_);

var status_ = (int)response_.StatusCode;
if (status_ == 200)
{
var objectResponse_ = await ReadObjectResponseAsync<UserResponseContractMessageContract>(response_, headers_, cancellationToken).ConfigureAwait(false);
if (objectResponse_.Object == null)
{
throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
}
return objectResponse_.Object;
}
else
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
}
}
finally
{
if (disposeResponse_)
response_.Dispose();
}
}
}
finally
{
if (disposeClient_)
client_.Dispose();
}
}

/// <returns>Success</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual System.Threading.Tasks.Task<string> TestAsync()
Expand Down Expand Up @@ -1570,6 +1648,52 @@ protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.Cal
}
}

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.19.0.0 (NJsonSchema v10.9.0.0 (Newtonsoft.Json v13.0.3.0))")]
public partial class RegenerateTokenContract : System.ComponentModel.INotifyPropertyChanged
{
private long _userId;
private System.Collections.Generic.ICollection<ClaimContract> _claims;

[Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public long UserId
{
get { return _userId; }

set
{
if (_userId != value)
{
_userId = value;
RaisePropertyChanged();
}
}
}

[Newtonsoft.Json.JsonProperty("claims", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public System.Collections.Generic.ICollection<ClaimContract> Claims
{
get { return _claims; }

set
{
if (_claims != value)
{
_claims = value;
RaisePropertyChanged();
}
}
}

public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.19.0.0 (NJsonSchema v10.9.0.0 (Newtonsoft.Json v13.0.3.0))")]
public partial class UserClaimContract : System.ComponentModel.INotifyPropertyChanged
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,55 @@
}
}
},
"/api/Users/RegenerateToken": {
"post": {
"tags": [
"Users"
],
"operationId": "RegenerateToken",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RegenerateTokenContract"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/RegenerateTokenContract"
}
},
"application/*+json": {
"schema": {
"$ref": "#/components/schemas/RegenerateTokenContract"
}
}
}
},
"responses": {
"200": {
"description": "Success",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/UserResponseContractMessageContract"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/UserResponseContractMessageContract"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/UserResponseContractMessageContract"
}
}
}
}
}
}
},
"/api/Users/Test": {
"get": {
"tags": [
Expand Down Expand Up @@ -736,6 +785,24 @@
}
}
},
"RegenerateTokenContract": {
"type": "object",
"additionalProperties": false,
"properties": {
"userId": {
"type": "integer",
"format": "int64"
},
"claims": {
"title": "List<ClaimContract>",
"type": "array",
"nullable": true,
"items": {
"$ref": "#/components/schemas/ClaimContract"
}
}
}
},
"UserClaimContract": {
"type": "object",
"additionalProperties": false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>0.0.0.5</Version>
<Version>0.0.0.6</Version>
<Description>client generated code.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>microservice,auth,authentication,client</PackageTags>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyMicroservices.AuthenticationsMicroservice.Contracts.Common
{
public class RegenerateTokenContract
{
public long UserId { get; set; }
public List<ClaimContract> Claims { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,8 @@ public JWTManager(IContractLogic<UserEntity, AddUserRequestContract, UserContrac

public virtual async Task<MessageContract<long>> Login(UserSummaryContract cred)
{
string Password = await AuthenticationHelper.HashPassword(cred.Password);

var userRecords = await _userLogic.GetAll();
var user = userRecords.Result.Where(x => x.UserName == cred.UserName && x.Password == Password);
var user = userRecords.Result.Where(x => x.UserName == cred.UserName && x.Password == cred.Password);
if (!user.Any())
return (FailedReasonType.AccessDenied, "Username or password is invalid."); //"Username or password is invalid."

Expand All @@ -48,9 +46,7 @@ public virtual async Task<MessageContract<UserResponseContract>> GenerateToken(U
if (!response)
return response.ToContract<UserResponseContract>();

string Password = await AuthenticationHelper.HashPassword(cred.Password);

var user = await _userLogic.GetBy(x => x.UserName == cred.UserName && x.Password == Password);
var user = await _userLogic.GetBy(x => x.UserName == cred.UserName && x.Password == cred.Password);

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_config.GetValue<string>("JWT:Key"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
using EasyMicroservices.AuthenticationsMicroservice.Contracts.Requests;
using EasyMicroservices.AuthenticationsMicroservice.Contracts.Responses;
using EasyMicroservices.AuthenticationsMicroservice.Database.Entities;
using EasyMicroservices.AuthenticationsMicroservice.Helpers;
using EasyMicroservices.AuthenticationsMicroservice.Interfaces;
using EasyMicroservices.Cores.AspCoreApi;
using EasyMicroservices.Cores.Database.Interfaces;
using EasyMicroservices.ServiceContracts;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
Expand Down Expand Up @@ -42,6 +44,9 @@ public async Task<MessageContract<long>> Register(AddUserRequestContract request
[HttpPost]
public async Task<MessageContract<long>> Login(UserSummaryContract request)
{
string password = await AuthenticationHelper.HashPassword(request.Password);
request.Password = password;

var response = await _jwtManager.Login(request);

return response;
Expand All @@ -51,11 +56,45 @@ public async Task<MessageContract<long>> Login(UserSummaryContract request)
[HttpPost]
public async Task<MessageContract<UserResponseContract>> GenerateToken(UserClaimContract request)
{
string password = await AuthenticationHelper.HashPassword(request.Password);
request.Password = password;

var response = await _jwtManager.GenerateToken(request);

return response;
}

[HttpPost]
public async Task<MessageContract<UserResponseContract>> RegenerateToken(RegenerateTokenContract request)
{
var user = await _contractLogic.GetById(new Cores.Contracts.Requests.GetIdRequestContract<long>
{
Id = request.UserId
});

if (user)
{

string password = user.Result.Password;

var req = new UserClaimContract
{
Password = password,
UserName = user.Result.UserName,
Claims = request.Claims
};

var response = await _jwtManager.GenerateToken(req);

return new UserResponseContract
{
Token = response.Result.Token
};
}

return user.ToContract<UserResponseContract>();
}

[HttpGet]
[Authorize]
public string Test()
Expand Down

0 comments on commit a980373

Please sign in to comment.