docs: unifying all references to login/logout actions

This commit is contained in:
Hamid Reza Mohammadi 2022-01-23 09:50:04 +03:30
parent 7fcd37ea1d
commit 4d3459496d
7 changed files with 148 additions and 359 deletions

View File

@ -34,11 +34,6 @@ namespace GanjooRazor.Pages
/// </summary>
private readonly IConfiguration Configuration;
/// <summary>
/// HttpClient instance
/// </summary>
private readonly HttpClient _httpClient;
/// <summary>
/// memory cache
/// </summary>
@ -71,10 +66,9 @@ namespace GanjooRazor.Pages
public IndexModel(IConfiguration configuration,
HttpClient httpClient,
IMemoryCache memoryCache
)
) : base(httpClient)
{
Configuration = configuration;
_httpClient = httpClient;
_memoryCache = memoryCache;
}
@ -90,100 +84,7 @@ namespace GanjooRazor.Pages
/// </summary>
public GanjoorSiteBannerViewModel Banner { get; set; }
/// <summary>
/// Login
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLoginAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
LoginViewModel.ClientAppName = "GanjooRazor";
LoginViewModel.Language = "fa-IR";
var stringContent = new StringContent(JsonConvert.SerializeObject(LoginViewModel), Encoding.UTF8, "application/json");
var loginUrl = $"{APIRoot.Url}/api/users/login";
var response = await _httpClient.PostAsync(loginUrl, stringContent);
if (response.StatusCode != HttpStatusCode.OK)
{
return Redirect($"/login?redirect={Request.Path}&error={JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync())}");
}
LoggedOnUserModelEx loggedOnUser = JsonConvert.DeserializeObject<LoggedOnUserModelEx>(await response.Content.ReadAsStringAsync());
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(365),
};
Response.Cookies.Append("UserId", loggedOnUser.User.Id.ToString(), cookieOption);
Response.Cookies.Append("SessionId", loggedOnUser.SessionId.ToString(), cookieOption);
Response.Cookies.Append("Token", loggedOnUser.Token, cookieOption);
Response.Cookies.Append("Username", loggedOnUser.User.Username, cookieOption);
Response.Cookies.Append("Name", $"{loggedOnUser.User.FirstName} {loggedOnUser.User.SureName}", cookieOption);
Response.Cookies.Append("NickName", $"{loggedOnUser.User.NickName}", cookieOption);
Response.Cookies.Append("KeepHistory", $"{loggedOnUser.KeepHistory}", cookieOption);
bool canEditContent = false;
var ganjoorEntity = loggedOnUser.SecurableItem.Where(s => s.ShortName == RMuseumSecurableItem.GanjoorEntityShortName).SingleOrDefault();
if (ganjoorEntity != null)
{
var op = ganjoorEntity.Operations.Where(o => o.ShortName == SecurableItem.ModifyOperationShortName).SingleOrDefault();
if (op != null)
{
canEditContent = op.Status;
}
}
Response.Cookies.Append("CanEdit", canEditContent.ToString(), cookieOption);
return Redirect(Request.Path);
}
/// <summary>
/// logout
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLogoutAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
if (!string.IsNullOrEmpty(Request.Cookies["SessionId"]) && !string.IsNullOrEmpty(Request.Cookies["UserId"]))
{
using (HttpClient secureClient = new HttpClient())
{
if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
{
var logoutUrl = $"{APIRoot.Url}/api/users/delsession?userId={Request.Cookies["UserId"]}&sessionId={Request.Cookies["SessionId"]}";
await secureClient.DeleteAsync(logoutUrl);
}
}
}
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(-1)
};
foreach (var cookieName in new string[] { "UserId", "SessionId", "Token", "Username", "Name", "NickName", "CanEdit", "KeepHistory" })
{
if (Request.Cookies[cookieName] != null)
{
Response.Cookies.Append(cookieName, "", cookieOption);
}
}
return Redirect(Request.Path);
}
public _CommentPartialModel GetCommentModel(GanjoorCommentSummaryViewModel comment)
{

View File

@ -23,7 +23,7 @@
<div id="login-container">
@if (Model.LoggedIn)
{
<form method="post">
<form method="post" action="?handler=Logout">
<table>
<tr>
<td><input type="submit" name="submit" id="submit" value="خروج" /></td>
@ -35,7 +35,7 @@
}
else
{
<form method="post">
<form method="post" action="?handler=Login">
<table>
<tr>
<td>

View File

@ -1,30 +1,13 @@
using GanjooRazor.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using RMuseum.Models.Auth.Memory;
using RMuseum.Models.Auth.ViewModel;
using RSecurityBackend.Models.Auth.Memory;
using RSecurityBackend.Models.Auth.ViewModels;
using System;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace GanjooRazor.Pages
{
[IgnoreAntiforgeryToken(Order = 1001)]
public class LoginModel : PageModel
public class LoginModel : LoginPartialEnabledPageModel
{
[BindProperty]
public LoginViewModel LoginViewModel { get; set; }
public bool LoggedIn { get; set; }
public LoginModel(HttpClient httpClient) : base(httpClient) { }
public string UserFriendlyName { get; set; }
public string LastError { get; set; }
@ -43,108 +26,5 @@ namespace GanjooRazor.Pages
}
}
public async Task<IActionResult> OnPostAsync()
{
RedirectUrl = Request.Query["redirect"];
if (string.IsNullOrEmpty(RedirectUrl))
{
RedirectUrl = "/";
}
if (!ModelState.IsValid)
{
return Page();
}
LoginViewModel.ClientAppName = "GanjooRazor";
LoginViewModel.Language = "fa-IR";
using (HttpClient secureClient = new HttpClient())
{
if(string.IsNullOrEmpty(LoginViewModel.Username))
{
if(await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
{
var logoutUrl = $"{APIRoot.Url}/api/users/delsession?userId={Request.Cookies["UserId"]}&sessionId={Request.Cookies["SessionId"]}";
await secureClient.DeleteAsync(logoutUrl);
}
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(-1)
};
foreach (var cookieName in new string[] { "UserId", "SessionId", "Token", "Username", "Name", "NickName", "CanEdit", "KeepHistory" })
{
if(Request.Cookies[cookieName] != null)
{
Response.Cookies.Append(cookieName, "", cookieOption);
}
}
return Page();
}
else
{
if (LoginViewModel == null)
{
LastError = "لطفاً پست الکترونیکی و گذرواژه‌تان را وارد کنید.";
return Page();
}
if (string.IsNullOrEmpty(LoginViewModel.Username) || string.IsNullOrEmpty(LoginViewModel.Password))
{
LastError = "لطفاً پست الکترونیکی و گذرواژه‌تان را وارد کنید.";
return Page();
}
var stringContent = new StringContent(JsonConvert.SerializeObject(LoginViewModel), Encoding.UTF8, "application/json");
var loginUrl = $"{APIRoot.Url}/api/users/login";
var response = await secureClient.PostAsync(loginUrl, stringContent);
if (response.StatusCode != HttpStatusCode.OK)
{
LastError = JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
return Page();
}
LoggedOnUserModelEx loggedOnUser = JsonConvert.DeserializeObject<LoggedOnUserModelEx>(await response.Content.ReadAsStringAsync());
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(365),
};
Response.Cookies.Append("UserId", loggedOnUser.User.Id.ToString(), cookieOption);
Response.Cookies.Append("SessionId", loggedOnUser.SessionId.ToString(), cookieOption);
Response.Cookies.Append("Token", loggedOnUser.Token, cookieOption);
Response.Cookies.Append("Username", loggedOnUser.User.Username, cookieOption);
Response.Cookies.Append("Name", $"{loggedOnUser.User.FirstName} {loggedOnUser.User.SureName}", cookieOption);
Response.Cookies.Append("NickName", $"{loggedOnUser.User.NickName}", cookieOption);
Response.Cookies.Append("KeepHistory", $"{loggedOnUser.KeepHistory}", cookieOption);
bool canEditContent = false;
var ganjoorEntity = loggedOnUser.SecurableItem.Where(s => s.ShortName == RMuseumSecurableItem.GanjoorEntityShortName).SingleOrDefault();
if (ganjoorEntity != null)
{
var op = ganjoorEntity.Operations.Where(o => o.ShortName == SecurableItem.ModifyOperationShortName).SingleOrDefault();
if (op != null)
{
canEditContent = op.Status;
}
}
Response.Cookies.Append("CanEdit", canEditContent.ToString(), cookieOption);
}
}
LastError = "Success!";
return Redirect(RedirectUrl);
}
}
}

View File

@ -1,6 +1,18 @@
using Microsoft.AspNetCore.Mvc;
using GanjooRazor.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using RMuseum.Models.Auth.Memory;
using RMuseum.Models.Auth.ViewModel;
using RSecurityBackend.Models.Auth.Memory;
using RSecurityBackend.Models.Auth.ViewModels;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace GanjooRazor.Pages
{
@ -13,5 +25,112 @@ namespace GanjooRazor.Pages
[BindProperty]
public LoginViewModel LoginViewModel { get; set; }
/// <summary>
/// logout
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLogoutAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
if (!string.IsNullOrEmpty(Request.Cookies["SessionId"]) && !string.IsNullOrEmpty(Request.Cookies["UserId"]))
{
using (HttpClient secureClient = new HttpClient())
{
if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
{
var logoutUrl = $"{APIRoot.Url}/api/users/delsession?userId={Request.Cookies["UserId"]}&sessionId={Request.Cookies["SessionId"]}";
await secureClient.DeleteAsync(logoutUrl);
}
}
}
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(-1)
};
foreach (var cookieName in new string[] { "UserId", "SessionId", "Token", "Username", "Name", "NickName", "CanEdit", "KeepHistory" })
{
if (Request.Cookies[cookieName] != null)
{
Response.Cookies.Append(cookieName, "", cookieOption);
}
}
return Redirect(Request.Path);
}
/// <summary>
/// Login
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLoginAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
LoginViewModel.ClientAppName = "GanjooRazor";
LoginViewModel.Language = "fa-IR";
var stringContent = new StringContent(JsonConvert.SerializeObject(LoginViewModel), Encoding.UTF8, "application/json");
var loginUrl = $"{APIRoot.Url}/api/users/login";
var response = await _httpClient.PostAsync(loginUrl, stringContent);
if (response.StatusCode != HttpStatusCode.OK)
{
return Redirect($"/login?redirect={Request.Path}&error={JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync())}");
}
LoggedOnUserModelEx loggedOnUser = JsonConvert.DeserializeObject<LoggedOnUserModelEx>(await response.Content.ReadAsStringAsync());
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(365),
};
Response.Cookies.Append("UserId", loggedOnUser.User.Id.ToString(), cookieOption);
Response.Cookies.Append("SessionId", loggedOnUser.SessionId.ToString(), cookieOption);
Response.Cookies.Append("Token", loggedOnUser.Token, cookieOption);
Response.Cookies.Append("Username", loggedOnUser.User.Username, cookieOption);
Response.Cookies.Append("Name", $"{loggedOnUser.User.FirstName} {loggedOnUser.User.SureName}", cookieOption);
Response.Cookies.Append("NickName", $"{loggedOnUser.User.NickName}", cookieOption);
Response.Cookies.Append("KeepHistory", $"{loggedOnUser.KeepHistory}", cookieOption);
bool canEditContent = false;
var ganjoorEntity = loggedOnUser.SecurableItem.Where(s => s.ShortName == RMuseumSecurableItem.GanjoorEntityShortName).SingleOrDefault();
if (ganjoorEntity != null)
{
var op = ganjoorEntity.Operations.Where(o => o.ShortName == SecurableItem.ModifyOperationShortName).SingleOrDefault();
if (op != null)
{
canEditContent = op.Status;
}
}
Response.Cookies.Append("CanEdit", canEditContent.ToString(), cookieOption);
return Redirect(Request.Path);
}
/// <summary>
/// HttpClient instance
/// </summary>
protected readonly HttpClient _httpClient;
public LoginPartialEnabledPageModel(
HttpClient httpClient
)
{
_httpClient = httpClient;
}
}
}

View File

@ -51,8 +51,10 @@
</div>
}
<div class="spacer"></div>
<partial name="_InlineLoginPartial" model="Model" />
</div>
</div>
<partial name="_FooterPartial" model="null" />
</div>

View File

@ -1,5 +1,4 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RMuseum.Models.Ganjoor.ViewModels;
@ -9,7 +8,8 @@ using System.Threading.Tasks;
namespace GanjooRazor.Pages
{
public class PhotosModel : PageModel
[IgnoreAntiforgeryToken(Order = 1001)]
public class PhotosModel : LoginPartialEnabledPageModel
{
public string LastError { get; set; }
@ -35,20 +35,15 @@ namespace GanjooRazor.Pages
}
public async Task<IActionResult> OnGetAsync()
{
LoggedIn = !string.IsNullOrEmpty(Request.Cookies["Token"]);
ViewData["Title"] = "تصاویر شاعران گنجور";
Poets = await _PreparePoets();
return Page();
}
/// <summary>
/// HttpClient instance
/// </summary>
private readonly HttpClient _httpClient;
public PhotosModel(HttpClient httpClient)
public PhotosModel(HttpClient httpClient) : base(httpClient)
{
_httpClient = httpClient;
}
}
}

View File

@ -3,36 +3,23 @@ using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DNTPersianUtils.Core;
using GanjooRazor.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RMuseum.Models.Auth.Memory;
using RMuseum.Models.Auth.ViewModel;
using RMuseum.Models.Ganjoor.ViewModels;
using RMuseum.Services.Implementation;
using RSecurityBackend.Models.Auth.Memory;
using RSecurityBackend.Models.Auth.ViewModels;
using RSecurityBackend.Models.Generic;
namespace GanjooRazor.Pages
{
[IgnoreAntiforgeryToken(Order = 1001)]
public class SearchModel : LoginPartialEnabledPageModel
{
/// <summary>
/// HttpClient instance
/// </summary>
private readonly HttpClient _httpClient;
/// <summary>
/// memory cache
@ -51,9 +38,8 @@ namespace GanjooRazor.Pages
/// <param name="httpClient"></param>
/// <param name="memoryCache"></param>
/// <param name="configuration"></param>
public SearchModel(HttpClient httpClient, IMemoryCache memoryCache, IConfiguration configuration)
public SearchModel(HttpClient httpClient, IMemoryCache memoryCache, IConfiguration configuration) : base(httpClient)
{
_httpClient = httpClient;
_memoryCache = memoryCache;
Configuration
= configuration;
@ -134,7 +120,7 @@ namespace GanjooRazor.Pages
public async Task<IActionResult> OnGetPoetInformationAsync(int id)
{
if(id == 0)
if (id == 0)
return new OkObjectResult(null);
var cacheKey = $"/api/ganjoor/poet/{id}";
if (!_memoryCache.TryGetValue(cacheKey, out GanjoorPoetCompleteViewModel poet))
@ -179,7 +165,7 @@ namespace GanjooRazor.Pages
}
else
{
if(!string.IsNullOrEmpty(Query))
if (!string.IsNullOrEmpty(Query))
{
ViewData["Title"] = $"گنجور » نتایج جستجو برای {Query}";
}
@ -187,7 +173,7 @@ namespace GanjooRazor.Pages
{
ViewData["Title"] = $"گنجور » جستجو";
}
}
if (PoetId != 0)
@ -217,14 +203,14 @@ namespace GanjooRazor.Pages
Poems = JArray.Parse(await searchQueryResponse.Content.ReadAsStringAsync()).ToObject<List<GanjoorPoemCompleteViewModel>>();
}
if(Poems != null && Poems.Count == 0)
if (Poems != null && Poems.Count == 0)
{
Poems = null;
}
if(Poems != null)
if (Poems != null)
{
// highlight searched word
string[] queryParts = Query.IndexOf('"') == 0 && Query.LastIndexOf('"') == (Query.Length - 1) ?
@ -240,7 +226,7 @@ namespace GanjooRazor.Pages
{
foreach (var queryPart in queryParts)
{
if(lines[i].IndexOf(queryPart) != -1)
if (lines[i].IndexOf(queryPart) != -1)
{
if (i > 0)
{
@ -249,14 +235,14 @@ namespace GanjooRazor.Pages
linesInExcerpt.Add(i - 1);
}
}
if(linesInExcerpt.IndexOf(i) == -1)
if (linesInExcerpt.IndexOf(i) == -1)
{
linesInExcerpt.Add(i);
}
if (i < (lines.Length - 1))
linesInExcerpt.Add(i + 1);
break;
}
}
@ -290,7 +276,7 @@ namespace GanjooRazor.Pages
}
if(searchQueryResponse != null)
if (searchQueryResponse != null)
{
string paginationMetadataJsonValue = searchQueryResponse.Headers.GetValues("paging-headers").FirstOrDefault();
@ -298,7 +284,7 @@ namespace GanjooRazor.Pages
{
PaginationMetadata paginationMetadata = JsonConvert.DeserializeObject<PaginationMetadata>(paginationMetadataJsonValue);
string catQuery = "";
if(!string.IsNullOrEmpty(Request.Query["cat"]))
if (!string.IsNullOrEmpty(Request.Query["cat"]))
{
catQuery = $"&cat={Request.Query["cat"]}";
}
@ -306,10 +292,10 @@ namespace GanjooRazor.Pages
}
}
}
return Page();
}
@ -351,100 +337,6 @@ namespace GanjooRazor.Pages
return htmlText;
}
/// <summary>
/// Login
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLoginAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
LoginViewModel.ClientAppName = "GanjooRazor";
LoginViewModel.Language = "fa-IR";
var stringContent = new StringContent(JsonConvert.SerializeObject(LoginViewModel), Encoding.UTF8, "application/json");
var loginUrl = $"{APIRoot.Url}/api/users/login";
var response = await _httpClient.PostAsync(loginUrl, stringContent);
if (response.StatusCode != HttpStatusCode.OK)
{
return Redirect($"/login?redirect={Request.Path}&error={JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync())}");
}
LoggedOnUserModelEx loggedOnUser = JsonConvert.DeserializeObject<LoggedOnUserModelEx>(await response.Content.ReadAsStringAsync());
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(365),
};
Response.Cookies.Append("UserId", loggedOnUser.User.Id.ToString(), cookieOption);
Response.Cookies.Append("SessionId", loggedOnUser.SessionId.ToString(), cookieOption);
Response.Cookies.Append("Token", loggedOnUser.Token, cookieOption);
Response.Cookies.Append("Username", loggedOnUser.User.Username, cookieOption);
Response.Cookies.Append("Name", $"{loggedOnUser.User.FirstName} {loggedOnUser.User.SureName}", cookieOption);
Response.Cookies.Append("NickName", $"{loggedOnUser.User.NickName}", cookieOption);
Response.Cookies.Append("KeepHistory", $"{loggedOnUser.KeepHistory}", cookieOption);
bool canEditContent = false;
var ganjoorEntity = loggedOnUser.SecurableItem.Where(s => s.ShortName == RMuseumSecurableItem.GanjoorEntityShortName).SingleOrDefault();
if (ganjoorEntity != null)
{
var op = ganjoorEntity.Operations.Where(o => o.ShortName == SecurableItem.ModifyOperationShortName).SingleOrDefault();
if (op != null)
{
canEditContent = op.Status;
}
}
Response.Cookies.Append("CanEdit", canEditContent.ToString(), cookieOption);
return Redirect(Request.Path);
}
/// <summary>
/// logout
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLogoutAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
if (!string.IsNullOrEmpty(Request.Cookies["SessionId"]) && !string.IsNullOrEmpty(Request.Cookies["UserId"]))
{
using (HttpClient secureClient = new HttpClient())
{
if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
{
var logoutUrl = $"{APIRoot.Url}/api/users/delsession?userId={Request.Cookies["UserId"]}&sessionId={Request.Cookies["SessionId"]}";
await secureClient.DeleteAsync(logoutUrl);
}
}
}
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(-1)
};
foreach (var cookieName in new string[] { "UserId", "SessionId", "Token", "Username", "Name", "NickName", "CanEdit", "KeepHistory" })
{
if (Request.Cookies[cookieName] != null)
{
Response.Cookies.Append(cookieName, "", cookieOption);
}
}
return Redirect(Request.Path);
}
}
}