Skip to content

Commit

Permalink
feat: add a demonstration
Browse files Browse the repository at this point in the history
  • Loading branch information
arthuridea committed Dec 15, 2023
1 parent 34f25ad commit c56d036
Show file tree
Hide file tree
Showing 19 changed files with 1,503 additions and 74 deletions.
1 change: 1 addition & 0 deletions NetCore.BaiduAIGC.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LLMServiceHub", "src\LLMSer
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "00.Global", "00.Global", "{3BBFC57A-DC8F-4F03-8370-FD6179AD317F}"
ProjectSection(SolutionItems) = preProject
.gitattributes = .gitattributes
.gitignore = .gitignore
Directory.Build.props = Directory.Build.props
LICENSE.md = LICENSE.md
Expand Down
17 changes: 17 additions & 0 deletions src/LLMServiceHub/Common/AppConsts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace LLMServiceHub.Common
{
/// <summary>
///
/// </summary>
public static class AppConsts
{
/// <summary>
/// The default authentication scheme
/// </summary>
public const string DefaultAuthScheme = "LLMService.Auth";
/// <summary>
/// The authentication cookie name
/// </summary>
public const string AuthCookieName = "LLMService.Auth";
}
}
23 changes: 23 additions & 0 deletions src/LLMServiceHub/Common/BuildInUser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace LLMServiceHub.Common
{
/// <summary>
///
/// </summary>
public class BuildInUser
{
/// <summary>
/// Gets or sets the name of the user.
/// </summary>
/// <value>
/// The name of the user.
/// </value>
public string UserName { get; set; }
/// <summary>
/// Gets or sets the password.
/// </summary>
/// <value>
/// The password.
/// </value>
public string Password { get; set; }
}
}
6 changes: 5 additions & 1 deletion src/LLMServiceHub/Controller/v1_0/BaiduApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using LLMService.Shared.Extensions;
using LLMService.Shared.ServiceInterfaces;
using LLMService.Shared.Models;
using Microsoft.AspNetCore.Identity;

namespace LLMServiceHub.Controller.v1_0
{
Expand All @@ -22,7 +23,10 @@ namespace LLMServiceHub.Controller.v1_0
/// </remarks>
/// <param name="baiduApiService">The baidu API service.</param>
/// <param name="ernieVilgApiService">The ernie vilg API service.</param>
//[Authorize]

// use oidc jwt authentication or local identity
//[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
[Route("api/v{version:apiVersion}/baidu")]
Expand Down
12 changes: 12 additions & 0 deletions src/LLMServiceHub/LLMServiceHub.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@
<Compile Remove="Common\HttpResponseExtensions.cs" />
</ItemGroup>

<ItemGroup>
<Content Remove="bundleconfig.json" />
</ItemGroup>

<ItemGroup>
<_ContentIncludedByDefault Remove="wwwroot\chat.html" />
</ItemGroup>

<ItemGroup>
<None Include="bundleconfig.json" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc" Version="7.1.1" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="7.1.0" />
Expand Down
271 changes: 267 additions & 4 deletions src/LLMServiceHub/Pages/Index.cshtml

Large diffs are not rendered by default.

147 changes: 144 additions & 3 deletions src/LLMServiceHub/Pages/Index.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
using Microsoft.AspNetCore.Mvc;
using LLMServiceHub.Common;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.IdentityModel.Tokens;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace LLMServiceHub.Pages
{
Expand All @@ -13,22 +23,153 @@ public class IndexModel : PageModel
/// The logger
/// </summary>
private readonly ILogger<IndexModel> _logger;
private readonly IConfiguration _configuration;

/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[BindProperty]
public InputModel Input { get; set; }

/// <summary>

Check warning on line 35 in src/LLMServiceHub/Pages/Index.cshtml.cs

View workflow job for this annotation

GitHub Actions / build

XML comment is not placed on a valid language element

Check warning on line 35 in src/LLMServiceHub/Pages/Index.cshtml.cs

View workflow job for this annotation

GitHub Actions / build

XML comment is not placed on a valid language element
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
//public IList<AuthenticationScheme> ExternalLogins { get; set; }

/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public string ReturnUrl { get; set; }

/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[TempData]
public string ErrorMessage { get; set; }

/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class InputModel
{
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Required]
public string UserName { get; set; }

/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}



/// <summary>
/// Initializes a new instance of the <see cref="IndexModel"/> class.
/// </summary>
/// <param name="config"></param>
/// <param name="logger">The logger.</param>
public IndexModel(ILogger<IndexModel> logger)
public IndexModel(
IConfiguration config,
ILogger<IndexModel> logger)
{
_configuration = config;
_logger = logger;
}

/// <summary>
/// Called when [get].
/// </summary>
public void OnGet()
public void OnGet(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}

returnUrl ??= Url.Content("~/");

ReturnUrl = returnUrl;
}

/// <summary>
/// Called when [post asynchronous].
/// </summary>
/// <param name="returnUrl">The return URL.</param>
/// <returns></returns>
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");

//ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = ValidateUser(Input.UserName, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
// set authentication cookie
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, Input.UserName),
new Claim(ClaimTypes.Role, "User")
};
var authProperties = new AuthenticationProperties
{
IsPersistent = Input.RememberMe,//是否持久化

//如果用户点“登录“进来,登录成功后跳转到首页,否则跳转到上一个页面
RedirectUri = string.IsNullOrWhiteSpace(returnUrl) ? "/Index" : returnUrl,
};
var identity = new ClaimsIdentity(claims, AppConsts.DefaultAuthScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(AppConsts.DefaultAuthScheme, principal, authProperties);
return LocalRedirect(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}

// If we got this far, something failed, redisplay form
return Page();
}

private (bool Succeeded, string Message) ValidateUser(string username, string password, bool persist = false)
{
var ret = (Succeeded: false, Message: "用户不存在");
var validusers = _configuration.GetSection("Users")
.Get<List<BuildInUser>>();
if(validusers.Any(x=> x.UserName== username && x.Password == password))
{
ret.Succeeded = true;
ret.Message = "Ok";
}
return ret;
}

}
}
58 changes: 22 additions & 36 deletions src/LLMServiceHub/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,49 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<html lang="zh-cn" data-bs-theme="light">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - RestClientApi</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/RestClientApi.styles.css" asp-append-version="true" />
<title>@ViewData["Title"]</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@@tabler/core@latest/dist/css/tabler.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@@tabler/core@latest/dist/css/tabler-flags.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@@tabler/core@latest/dist/css/tabler-payments.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@@tabler/core@latest/dist/css/tabler-vendors.min.css">
@await RenderSectionAsync("Headers", required: false)
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">RestClientApi</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
</ul>
<body class="layout-fluid">
<div class="page">
<header class="navbar navbar-expand-sm navbar-light d-print-none vh-5">
<div class="container-xl">
<h1 class="h3 navbar-brand navbar-brand-autodark d-none-navbar-horizontal pe-0 pe-md-3">
<a class="navbar-brand" asp-area="" asp-page="/Index">@ViewData["Title"]</a>
</h1>

<div class="navbar-nav flex-row order-md-last">
<partial name="_LoginPartial" />
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
</header>

<footer class="border-top footer text-muted">
<div class="container">
&copy; 2023 - RestClientApi - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
@RenderBody()
</div>


<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@@tabler/core@latest/dist/js/tabler.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

@await RenderSectionAsync("Scripts", required: false)
Expand Down
27 changes: 27 additions & 0 deletions src/LLMServiceHub/Pages/Shared/_LoginPartial.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@if(User.Identity.IsAuthenticated){

<div class="nav-item">
<a href="javascript:void(0)" class="nav-link d-flex lh-1 text-reset p-0">
<span class="avatar avatar-sm"></span>
<div class="d-none d-xl-block ps-2">
<div></div>
<div class="mt-1 small text-secondary">测试用户</div>
</div>
</a>
</div>
<div class="nav-item">
<!-- Download SVG icon from http://tabler-icons.io/i/dots-vertical -->
<svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"></path><path d="M12 19m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"></path><path d="M12 5m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"></path></svg>

</div>
<div class="nav-item">
<a asp-page="SignOut" class="nav-link d-flex lh-1 text-reset p-0">
退出登录
</a>
</div>
}
else{
<div class="nav-item">
<span>尚未登录</span>
</div>
}
4 changes: 4 additions & 0 deletions src/LLMServiceHub/Pages/SignOut.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
@page
@model LLMServiceHub.Pages.SignOutModel
@{
}
29 changes: 29 additions & 0 deletions src/LLMServiceHub/Pages/SignOut.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using LLMServiceHub.Common;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LLMServiceHub.Pages
{
/// <summary>
///
/// </summary>
/// <seealso cref="Microsoft.AspNetCore.Mvc.RazorPages.PageModel" />
public class SignOutModel : PageModel
{
/// <summary>
/// Called when [get].
/// </summary>
public async Task<IActionResult> OnGetAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
//await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
await HttpContext.SignOutAsync(AppConsts.DefaultAuthScheme);

return LocalRedirect(returnUrl);
}
}
}
Loading

0 comments on commit c56d036

Please sign in to comment.