Skip to content

Commit

Permalink
Merge pull request #33 from RemmSoft/feature/Core-31-1
Browse files Browse the repository at this point in the history
#31 : User module done.
  • Loading branch information
tanser authored Sep 12, 2017
2 parents 0915bb3 + a101dac commit 8851c02
Show file tree
Hide file tree
Showing 5 changed files with 178 additions and 51 deletions.
145 changes: 98 additions & 47 deletions RS.Core.Api/Controllers/Account/AccountController.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using RS.Core.Const;
using RS.Core.Models;
using RS.Core.Providers;
using RS.Core.Results;
using RS.Core.Service.DTOs;
using RS.Core.Service;
using RS.Core.Const;
using RS.Core.Service.DTOs;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;

namespace RS.Core.Controllers
{
Expand Down Expand Up @@ -131,7 +131,7 @@ public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel m

IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
model.NewPassword);

if (!result.Succeeded)
{
return GetErrorResult(result);
Expand Down Expand Up @@ -264,9 +264,9 @@ public async Task<IHttpActionResult> GetExternalLogin(string provider, string er
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);

Expand Down Expand Up @@ -339,7 +339,7 @@ public async Task<IHttpActionResult> Register(RegisterBindingModel model)
//You can implement your external user table.
#region ExternalUserTable

APIResult customUserResult = await userService.Add(model, Guid.Parse(user.Id));
APIResult customUserResult = await userService.Register(model, Guid.Parse(user.Id));

if (customUserResult.Message != Messages.Ok)
return Content(HttpStatusCode.BadRequest, customUserResult);
Expand Down Expand Up @@ -385,48 +385,99 @@ public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingMod
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (!result.Succeeded)
{
return GetErrorResult(result);
return GetErrorResult(result);
}
return Ok();
}

////GET api/Account/RemindPassword?=Email
//[AllowAnonymous]
//[Route("RemindPassword"), HttpGet]
//public async Task<IHttpActionResult> RemindPassword(string email)
//{
// var user = await UserManager.FindByEmailAsync(email);
// if (user == null)
// return BadRequest(Messages.GNE0001);
// PUT api/Account/Update
[Route("Update"), HttpPut]
public async Task<IHttpActionResult> Update(UserUpdateDto model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);

var result = await userService.Update(model, IdentityClaimsValues.UserID<Guid>());

if (result.Message != Messages.Ok)
return Content(HttpStatusCode.BadRequest, result);

return Ok(result);
}

// GET api/Account/RemindPassword?=email
[AllowAnonymous]
[Route("RemindPassword"), HttpGet]
public async Task<IHttpActionResult> RemindPassword(string email)
{
var user = await UserManager.FindByEmailAsync(email);
if (user == null)
return BadRequest(Messages.GNE0001);

string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

var result = userService.RemindPassword(email, code, user.Id);

if (result.Message != Messages.Ok)
return Content(HttpStatusCode.BadRequest, result);

return Ok(result);
}

// POST api/Account/ResetPassword
[AllowAnonymous]
[Route("ResetPassword"), HttpPost]
public async Task<IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

IdentityResult result = await UserManager.ResetPasswordAsync(model.ID, model.Code, model.NewPassword);

// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
if (!result.Succeeded)
{
return GetErrorResult(result);
}

// var result = userService.RemindPasswordMail(email, code, user.Id);
return Ok();
}

// if (result.Message != Messages.Ok)
// return Content(HttpStatusCode.BadRequest, result);
// GET api/Account/Get
[Route("Get"), HttpGet]
[ResponseType(typeof(IEnumerable<UserListDto>))]
public async Task<IHttpActionResult> GetByID(Guid id)
{
var result = await userService.GetByID(id);

// return Ok(result);
//}
return Ok(result);
}

////POST api/Account/ResetPassword
//[AllowAnonymous, Route("ResetPassword"), HttpPost]
//public async Task<IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// GET api/Account/Get
[Route("Get"), HttpGet]
[ResponseType(typeof(IEnumerable<UserListDto>))]
public async Task<IHttpActionResult> GetList(string name = null, string email = null)
{
var result = await userService.GetList(name, email);

if (result == null || result.Count <= 0)
result = new List<UserListDto>();

// IdentityResult result = await UserManager.ResetPasswordAsync(model.ID, model.Code, model.NewPassword);
return Ok(result);
}

// if (!result.Succeeded)
// {
// return GetErrorResult(result);
// }
// GET api/Account/GetSelectList
[Route("GetSelectList"), HttpGet]
public async Task<IHttpActionResult> AutoCompleteList(Guid? id = null, string text = null)
{
var result = await userService.AutoCompleteList(id, text);

// return Ok();
//}
if (result == null)
return Content(HttpStatusCode.OK, new string[0]);

return Ok(result);
}

protected override void Dispose(bool disposing)
{
Expand Down
21 changes: 21 additions & 0 deletions RS.Core.Api/Models/AccountBindingModels.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,25 @@ public class SetPasswordBindingModel
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

public class ResetPasswordBindingModel
{
[Required]
[Display(Name = "Code")]
public string Code { get; set; }

[Required]
public string ID { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
4 changes: 3 additions & 1 deletion RS.Core.Api/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
<!-- Develop DB Context -->
<add name="RSCoreDBContext" connectionString="Data Source=.;Initial Catalog=RSCore_Develop;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings></appSettings>
<appSettings>
<add key="resetPasswordUrl" value="MyProject/Account/ResetPasswordScreen"/>
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
Expand Down
1 change: 1 addition & 0 deletions RS.Core.Service/RS.Core.Service.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll</HintPath>
Expand Down
58 changes: 55 additions & 3 deletions RS.Core.Service/Services/User/UserService.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,35 @@
using AutoMapper;
using AutoMapper.QueryableExtensions;
using RS.Core.Const;
using RS.Core.Domain;
using RS.Core.Lib.Email;
using RS.Core.Service.DTOs;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace RS.Core.Service
{
public interface IUserService : IBaseService<UserAddDto, UserUpdateDto,UserCardDto,User,Guid>
{
Task<APIResult> Add(UserAddDto model, Guid identityUserID);
Task<APIResult> Register(UserAddDto model, Guid identityUserID);
APIResult RemindPassword(string email, string code, string id);
Task<IList<UserListDto>> GetList(string name = null, string email = null);
}

public class UserService : BaseService<UserAddDto, UserUpdateDto, UserCardDto, User, Guid>, IUserService
{
public UserService(EntityUnitofWork<Guid> _uow) : base(_uow)
private IEmailService emailService;
public UserService(EntityUnitofWork<Guid> _uow, IEmailService _emailService) : base(_uow)
{
emailService = _emailService;
}

public async Task<APIResult> Add(UserAddDto model, Guid identityUserID)
public async Task<APIResult> Register(UserAddDto model, Guid identityUserID)
{
var duplicateUserCheck = await uow.Repository<User>().Query().AnyAsync(x => x.Email == model.Email);
if (duplicateUserCheck)
Expand All @@ -36,5 +46,47 @@ public async Task<APIResult> Add(UserAddDto model, Guid identityUserID)

return new APIResult { Data = entity.ID, Message = Messages.Ok };
}

public APIResult RemindPassword(string email, string code, string id)
{
try
{
ArrayList EmailGroup = new ArrayList();
EmailGroup.Add(email);

EmailDto emailModel = new EmailDto
{
EmailGroup = EmailGroup,
Subject = "RS Support",
BackgroundColor = "b61528",
Header = "Password Change Request",
Content = "We understand you're having trouble logging into your account. We can help you regain access to your account. " +
"You can create a new password by clicking on the 'Change Password' button If this is not the case, you can ask our support team for help by emailing support@remmsoft.com.",
ButtonValue = "Change Password",
//`resetPasswordUrl` is get from Web.Config.
URL = ConfigurationManager.AppSettings["resetPasswordUrl"] + "?id=" + id + "?code=" + code
};

emailService.SendMail(emailModel);
return new APIResult { Message = Messages.Ok };
}
catch (Exception ex)
{
return new APIResult { Message = ex.Message };
}
}

public async Task<IList<UserListDto>> GetList(string name=null, string email=null)
{
var query = uow.Repository<User>().Query();

if (name != null)
query = query.Where(x => x.Name.Contains(name));
if (email != null)
query = query.Where(x => x.Email.Contains(email));

return await query.ProjectTo<UserListDto>().ToListAsync();
}

}
}

0 comments on commit 8851c02

Please sign in to comment.