Skip to content

Commit

Permalink
#37 Upgraded Identity on table name change, added properties, updated…
Browse files Browse the repository at this point in the history
… setup, switched to use UserId instead of UserName on Post.
  • Loading branch information
Ray Fan committed Oct 10, 2017
1 parent 6bcf7b7 commit 3c94eb7
Show file tree
Hide file tree
Showing 28 changed files with 603 additions and 106 deletions.
37 changes: 30 additions & 7 deletions src/Fan.Web/Controllers/BlogController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,19 @@ public class BlogController : Controller
{
private readonly IBlogService _blogSvc;
private readonly UserManager<User> _userManager;
private readonly RoleManager<Role> _roleManager;
private readonly SignInManager<User> _signInManager;
private readonly ILogger<BlogService> _logger;
private readonly ILogger<BlogController> _logger;

public BlogController(IBlogService blogService,
UserManager<User> userManager,
RoleManager<Role> roleManager,
SignInManager<User> signInManager,
ILogger<BlogService> logger)
ILogger<BlogController> logger)
{
_blogSvc = blogService;
_userManager = userManager;
_roleManager = roleManager;
_signInManager = signInManager;
_logger = logger;
}
Expand Down Expand Up @@ -53,7 +56,7 @@ public async Task<IActionResult> Setup()
}

/// <summary>
/// Setting up the blog, create user, create blogsettings and default category.
/// Sets up the blog, creates user, role, blogsettings and default category.
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
Expand All @@ -63,14 +66,33 @@ public async Task<IActionResult> Setup(SetupViewModel model)
{
if (ModelState.IsValid)
{
_logger.LogInformation("Fanray Setup Begins");

// user with email as username
var user = new User { UserName = model.Email, Email = model.Email, DisplayName = model.DisplayName };
var adminRole = "Admin";
var role = new Role { Name = adminRole, IsSystemRole = true };

// create user
var user = new User { UserName = model.UserName, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);

// create Admin role
if (result.Succeeded)
{
_logger.LogInformation("{@User} account created with password.", user);
result = await _roleManager.CreateAsync(role);
}

// assign Admin role to user
if (result.Succeeded)
{
_logger.LogInformation("{@Role} created.", role);
result = await _userManager.AddToRoleAsync(user, adminRole);
}

if (result.Succeeded)
{
_logger.LogInformation("Blog Setup begins.");
_logger.LogInformation("User account created with password.");
_logger.LogInformation("{@Role} assigned to {@User}.", role, user);

//// sign-in user
//await _signInManager.SignInAsync(user, isPersistent: false);
Expand All @@ -79,6 +101,7 @@ public async Task<IActionResult> Setup(SetupViewModel model)
// create blog settings
await _blogSvc.CreateSettingsAsync(new BlogSettings {
Title = model.Title,
Tagline = model.Tagline,
TimeZoneId = model.TimeZoneId
});
_logger.LogInformation("BlogSettings created.");
Expand All @@ -90,7 +113,7 @@ await _blogSvc.CreatePostAsync(new BlogPost
TagTitles = null,
Title = Const.WELCOME_POST_TITLE,
Body = Const.WELCOME_POST_BODY,
UserName = model.UserName,
UserId = 1,
Status = EPostStatus.Published,
CommentStatus = ECommentStatus.AllowComments,
CreatedOn = DateTime.Now,
Expand Down
2 changes: 1 addition & 1 deletion src/Fan.Web/Controllers/ManageController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ public async Task<IActionResult> LinkLoginCallback()
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}

var info = await _signInManager.GetExternalLoginInfoAsync(user.Id);
var info = await _signInManager.GetExternalLoginInfoAsync(user.Id.ToString());
if (info == null)
{
throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
Expand Down
4 changes: 2 additions & 2 deletions src/Fan.Web/Extensions/UrlHelperExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Mvc
{
public static class UrlHelperExtensions
{
public static string EmailConfirmationLink(this IUrlHelper urlHelper, string userId, string code, string scheme)
public static string EmailConfirmationLink(this IUrlHelper urlHelper, int userId, string code, string scheme)
{
return urlHelper.Action(
action: nameof(AccountController.ConfirmEmail),
Expand All @@ -17,7 +17,7 @@ public static string EmailConfirmationLink(this IUrlHelper urlHelper, string use
protocol: scheme);
}

public static string ResetPasswordCallbackLink(this IUrlHelper urlHelper, string userId, string code, string scheme)
public static string ResetPasswordCallbackLink(this IUrlHelper urlHelper, int userId, string code, string scheme)
{
return urlHelper.Action(
action: nameof(AccountController.ResetPassword),
Expand Down
23 changes: 18 additions & 5 deletions src/Fan.Web/MetaWeblog/MetaWeblogService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,20 @@ namespace Fan.Web.MetaWeblog
{
public class MetaWeblogService : IMetaWeblogService
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IBlogService _blogSvc;
private readonly ILogger<MetaWeblogService> _logger;
private readonly IHostingEnvironment _hostingEnvironment;

public MetaWeblogService(SignInManager<User> signInManager,
public MetaWeblogService(
UserManager<User> userManager,
SignInManager<User> signInManager,
IBlogService blogSvc,
ILogger<MetaWeblogService> logger,
IHostingEnvironment env)
{
_userManager = userManager;
_signInManager = signInManager;
_blogSvc = blogSvc;
_logger = logger;
Expand All @@ -41,7 +45,7 @@ public async Task<string> NewPostAsync(string blogid, string userName, string pa
{
var blogPost = new BlogPost
{
UserName = String.IsNullOrEmpty(post.Author) ? userName : post.Author,
UserId = (await _userManager.FindByNameAsync(userName)).Id,
Title = post.Title,
Slug = post.Slug,
Body = post.Description,
Expand Down Expand Up @@ -73,7 +77,7 @@ public async Task<bool> EditPostAsync(string postId, string userName, string pas
var blogPost = new BlogPost
{
Id = Convert.ToInt32(postId),
UserName = String.IsNullOrEmpty(post.Author) ? userName : post.Author,
UserId = (await _userManager.FindByNameAsync(userName)).Id,
Title = post.Title,
Slug = post.Slug,
Body = post.Description,
Expand Down Expand Up @@ -246,6 +250,9 @@ public async Task<MetaMediaInfo> NewMediaObjectAsync(string blogId, string userN

try
{
// userId
int userId = (await _userManager.FindByNameAsync(userName)).Id;

// filename
string mediaObjectName = mediaObject.Name.Replace(" ", "_").Replace(":", "-");
var fileName = mediaObjectName.Substring(mediaObjectName.LastIndexOf('/') + 1);
Expand Down Expand Up @@ -281,7 +288,7 @@ public async Task<MetaMediaInfo> NewMediaObjectAsync(string blogId, string userN
// create media to db
await _blogSvc.UpsertMediaAsync(new Media
{
UserName = userName,
UserId = userId,
Title = fileName,
Slug = fileName,
MimeType = MimeTypeMap.GetMimeType(Path.GetExtension(fileName)), // mediaObject.type
Expand All @@ -303,6 +310,12 @@ await _blogSvc.UpsertMediaAsync(new Media

// -------------------------------------------------------------------- Private helpers

/// <summary>
/// Ensures user is valid by sign in, throws <see cref="MetaWeblogException"/> if sign in fails.
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
private async Task EnsureValidUserAsync(string userName, string password)
{
if (!await _signInManager.CanSignInAsync(new User { UserName = userName, PasswordHash = password }))
Expand All @@ -315,7 +328,7 @@ private MetaPost ToMetaPost(BlogPost blogPost, string rootUrl)
{
return new MetaPost
{
Author = blogPost.UserName,
AuthorId = blogPost.UserId.ToString(),
Categories = new List<string> { blogPost.CategoryTitle },
CommentPolicy = (blogPost.CommentStatus == ECommentStatus.AllowComments ||
blogPost.CommentStatus == ECommentStatus.AllowCommentsWithApproval) ? "1" : "0",
Expand Down
2 changes: 1 addition & 1 deletion src/Fan.Web/MetaWeblog/Models/MetaPost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public MetaPost()
}

public string PostId { get; set; }
public string Author { get; set; }
public string AuthorId { get; set; }
public string CommentPolicy { get; set; }
public string Title { get; set; }
public string Slug { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion src/Fan.Web/MetaWeblog/XmlRpcHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ private MetaPost ParseMetaPost(XElement ele)

// author
var authorId = memberList.SingleOrDefault(m => m.Element("name").Value == "wp_author_id");
post.Author = authorId?.Element("value").Value;
post.AuthorId = authorId?.Element("value").Value;

// categories
var categories = memberList.SingleOrDefault(m => m.Element("name").Value == "categories");
Expand Down
15 changes: 10 additions & 5 deletions src/Fan.Web/Models/BlogViewModels/SetupViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,32 @@ public SetupViewModel()
TimeZoneId = "Pacific Standard Time";
}


[Required]
[Display(Name = "Blog Name")]
[Display(Name = "Site Title")]
[StringLength(64, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)]
public string Title { get; set; }

[Display(Name = "Site Tagline")]
[StringLength(128, ErrorMessage = "The {0} must be no more than {1} characters long.", MinimumLength = 0)]
public string Tagline { get; set; }

public string TimeZoneId { get; set; }

[Display(Name = "Time Zone")]
public List<SelectListItem> TimeZones { get; set; }

[Required]
[Display(Name = "Username")]
public string UserName { get; set; }
[Display(Name = "Display Name")]
[StringLength(64, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)]
public string DisplayName { get; set; }

[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 4)]
[StringLength(16, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 4)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
Expand Down
12 changes: 8 additions & 4 deletions src/Fan.Web/Models/SeedData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

namespace Fan.Web
{
/// <summary>
/// Seed initial data. Not currently used instead a setup page is used.
/// </summary>
public class SeedData
{
public static async Task InitializeAsync(IServiceProvider serviceProvider)
Expand Down Expand Up @@ -46,7 +49,8 @@ private static async Task InsertData(IServiceProvider provider, FanDbContext db)
var data = provider.GetService<IOptions<SeedData>>().Value;

// data
string userName = "admin";
int userId = 1;
string displayName = "John Smith";
string password = "admin";
string email = "admin@notset.com";
string categoryTitle = "Uncategorized";
Expand All @@ -61,8 +65,8 @@ private static async Task InsertData(IServiceProvider provider, FanDbContext db)
logger.LogInformation("BlogSettings created.");

// User
await userManager.CreateAsync(user: new User { UserName = userName, Email = email }, password: password); // AccountController Login and LoginViewModel
logger.LogInformation($"User '{userName}' created.");
await userManager.CreateAsync(user: new User { DisplayName = displayName, UserName = email, Email = email }, password: password); // AccountController Login and LoginViewModel
logger.LogInformation($"User '{userId}' created.");

// Post / Category
if (seedWelcomePost)
Expand All @@ -73,7 +77,7 @@ await blogSvc.CreatePostAsync(new BlogPost
TagTitles = null,
Title = postTitle,
Body = postBody,
UserName = userName,
UserId = userId,
Status = EPostStatus.Published,
CommentStatus = ECommentStatus.AllowComments,
CreatedOn = DateTime.Now,
Expand Down
4 changes: 2 additions & 2 deletions src/Fan.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void ConfigureServices(IServiceCollection services)
});

// Identity
services.AddIdentity<User, IdentityRole>(options =>
services.AddIdentity<User, Role>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 4;
Expand Down Expand Up @@ -115,7 +115,7 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<FanDbContext>();
// you can create db here or you can click apply migrations when site launches
// when develop with migration, comment below out, if you decide to keep migration, consider use Migrate().
db.Database.EnsureCreated();
}
}
Expand Down
21 changes: 16 additions & 5 deletions src/Fan.Web/Views/Blog/Setup.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@
border: none;
background-color: #5091FF
}
.text-setup {
padding-left: 5px;
font-size: smaller;
}
</style>
</head>
<body>
Expand All @@ -48,23 +52,30 @@
<div class="col-lg-8 col-md-10 col-centered" style="margin-top:2rem">
<form method="post">
<h2>Fanray Blog Setup</h2>
<div asp-validation-summary="All" class="text-danger"></div>
<hr />

<div class="form-group">
<label asp-for="Title"></label>
<label asp-for="Title"></label><span class="text-setup">(Site name to show up on header and copyright)</span>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Tagline"></label><span class="text-setup">(Optional, in a few words explain what this site is about)</span>
<input asp-for="Tagline" class="form-control" />
<span asp-validation-for="Tagline" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeZones"></label>
<select asp-for="TimeZoneId" asp-items="Model.TimeZones" class="form-control"></select>
</div>
<div class="form-group">
<label asp-for="UserName"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
<label asp-for="DisplayName"></label><span class="text-setup">(Your name public will see when you post)</span>
<input asp-for="DisplayName" class="form-control" />
<span asp-validation-for="DisplayName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email"></label>
<label asp-for="Email"></label><span class="text-setup">(Used for login)</span>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/Fan.Web/Views/Blog/_PostInfo.cshtml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
@model BlogPost

<div class="post-info clearfix">
<i class="fa fa-user" aria-hidden="true"></i><span class="post-author">@Model.UserName</span>
<i class="fa fa-user" aria-hidden="true"></i><span class="post-author">@Model.User.DisplayName</span>
<i class="fa fa-calendar" aria-hidden="true"></i><span class="post-date">@Model.CreatedOnDisplay</span>
<i class="fa fa-folder" aria-hidden="true"></i><span class="post-category"><a href="@Model.Category.RelativeLink">@Model.CategoryTitle</a></span>
@if (Model.Tags.Count > 0)
Expand Down
2 changes: 1 addition & 1 deletion src/Fan.Web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"copy:bootstrap": "cpx node_modules/bootstrap/dist/** wwwroot/lib/bootstrap/dist",
"copy:jquery": "cpx node_modules/jquery/dist/* wwwroot/lib/jquery/dist",
"copy:jquery-val": "cpx node_modules/jquery-validation/dist/* wwwroot/lib/jquery-validation/dist",
"copy:jquery-val-unob": "cpx node_modules/jquery-validation-unobtrusive/dist/* wwwroot/lib/jquery-validation-unobtrusive/dist",
"copy:jquery-val-unob": "cpx node_modules/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js wwwroot/lib/jquery-validation-unobtrusive",
"copy:js": "cpx client/js/*.js wwwroot/js",
"copy:images": "cpx client/images wwwroot/images",
"copy:fontcss": "cpx node_modules/font-awesome/css/** wwwroot/lib/font-awesome/css",
Expand Down
Loading

0 comments on commit 3c94eb7

Please sign in to comment.