using AutoMapper; using HRM.DA; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Threading.Tasks; using HRM.BO; using System.Net.Http; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Options; using Erecruitment.UI.Api; using System.Text; using HRM.BO.Configuration; using Newtonsoft.Json; using System.Data; using System.Net; using System.Reflection; using Erecruitment.UI.DTOs.Auth; using Google.Apis.Auth; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Authentication; using System.IO; using Microsoft.AspNetCore.Server.IIS.Core; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.AspNetCore.Components.Routing; namespace Erecruitment.UI.Controllers { [ApiController] [Route("api/Authentication")] [Authorize] public class AuthController : ControllerBase { private readonly IConfiguration _config; private readonly IMapper _mapper; //private readonly IUserService _userService; private readonly IErJobUserService _erJobUserService; private readonly IBookmarkService _bookmarkService; private readonly ISystemConfigaration _systemConfig; private readonly string Secret; private readonly string GoogleClientId; private readonly IUserRoleService _userRoleService; private readonly IRoleService _roleService; private readonly IPayrollTypeService _payrollTypeService; private readonly IPasswordHistoryService _passwordHistoryService; private readonly IUserAccessTypeService _userAccessTypeService; private readonly IOptions _emailSettings; private readonly HttpClient _httpClient; public AuthController(IConfiguration config, IMapper mapper, IErJobUserService erJobUserService, IOptions appSettings, ISystemConfigaration sysconfig , IUserRoleService userRole, IRoleService rService, IPayrollTypeService pTypeService, IUserAccessTypeService uaccesstypesrv, IPasswordHistoryService passwordHistoryService, IOptions emailSettings, IBookmarkService bookmarkService) { _config = config; _mapper = mapper; // _userService = userService; this.Secret = appSettings.Value.Secret; _erJobUserService = erJobUserService; this._systemConfig = sysconfig; this._userRoleService = userRole; this._roleService = rService; this._payrollTypeService = pTypeService; this._userAccessTypeService = uaccesstypesrv; this._passwordHistoryService = passwordHistoryService; this._emailSettings = emailSettings; this._bookmarkService = bookmarkService; this.GoogleClientId = appSettings.Value.GoogleClientId; } /// /// /// /// /// //[HttpPost("login")] //[AllowAnonymous] //public IActionResult Login(UserForLoginDto userForLoginDto) //{ // //var hostName = Dns.GetHostEntry(HttpContext.Connection.RemoteIpAddress).HostName; // var userFromRepo = // _userService.GetByLoginIDAndPassword(userForLoginDto.Username.ToLower(), userForLoginDto.Password); // if (userFromRepo == null) // return BadRequest("Login ID/Password is invalid"); // if (userFromRepo.UserType == EnumUserType.User && // (userForLoginDto.nextPayProcessDate == null || userForLoginDto.payrollTypeid == null)) // { // return BadRequest("Access Type and process date is not valid."); // } // else // { // DateTime eocd = _userService.GetEndofContractDate(userForLoginDto.Username); // if (eocd != DateTime.MinValue && eocd < DateTime.Today) // { // return BadRequest("Login ID/Password is invalid"); // } // } // var key = Encoding.ASCII.GetBytes(this.Secret); // PayrollType payrollType = null; // if (userForLoginDto.payrollTypeid != null) // { // payrollType = new PayrollTypeService().Get((int)userForLoginDto.payrollTypeid); // } // var claims = new[] // { // new Claim("UserID", userFromRepo.ID.ToString()), // new Claim("LoginID", userFromRepo.LoginID), // new Claim("UserName", userFromRepo.UserName), // new Claim("UserType", ((int) userFromRepo.UserType).ToString()), // new Claim("ChangePasswordAtNextLogon", userFromRepo.ChangePasswordAtNextLogon.ToString()), // new Claim("EmployeeID", (userFromRepo.EmployeeID == null) ? "0" : userFromRepo.EmployeeID.ToString()), // new Claim("PayrollTypeID", // (userForLoginDto.payrollTypeid == null) ? "0" : ((int) userForLoginDto.payrollTypeid).ToString()), // new Claim("taxParamId", (payrollType == null) ? "0" : payrollType.TaxParamID.ToString()), // new Claim("nextPayProcessDate", (userForLoginDto.nextPayProcessDate == null) ? "null" : userForLoginDto.nextPayProcessDate.ToString()) // }; // var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature); // var tokenDescriptor = new SecurityTokenDescriptor // { // Subject = new ClaimsIdentity(claims), // Expires = DateTime.Now.AddDays(1), // SigningCredentials = creds // }; // var tokenHandler = new JwtSecurityTokenHandler(); // var token = tokenHandler.CreateToken(tokenDescriptor); // string userToken = tokenHandler.WriteToken(token); // if (userToken != null) // { // HttpContext.Session.SetString("JWToken", userToken); // } // return Ok(userToken); //} [HttpGet] [Route("GetPayrollTypesByLoginID/{LoginID}")] [AllowAnonymous] public ActionResult GetPayrollTypesByLoginID(string LoginID) { List payrollTypes = new List(); try { payrollTypes = this._payrollTypeService.GetPayrollTypes(LoginID); return Ok(payrollTypes); } catch (Exception ex) { //return ex; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpGet] [Route("GetPayrollTypeByLoginID")] public ActionResult GetPayrollTypeByLoginID() { PayrollType payrollType = null; CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); try { payrollType = this._payrollTypeService.Get((int)currentUser.PayrollTypeID); return Ok(payrollType); } catch (Exception ex) { //return ex; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } //[HttpGet] //[Route("GetUsers/{userType}/{LogInID}/{Name}")] //public ActionResult GetUsers(EnumUserType userType, string LogInID, string Name) //{ // LogInID = GlobalFunctions.GetApiDefaultData(LogInID); // Name = GlobalFunctions.GetApiDefaultData(Name); // try // { // List olist = _userService.Get(LogInID, Name, userType); // return Ok(olist); // } // catch (Exception ex) // { // //return ex; // return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); // } //} [HttpGet] [Route("GetLogInUserType")] public ActionResult GetLogInUserType() { CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); try { return Ok(currentUser.UserType); } catch (Exception ex) { //return ex; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpGet] [Route("GetCurrentUser")] public ActionResult GetCurrentUser() { CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); try { return Ok(currentUser); } catch (Exception ex) { //return ex; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } //[HttpGet] //[Route("GetUserByLoingID/{loginid}/{systemType}")] //public ActionResult GetUserByLoingID(string loginid, EnumSystemType systemType) //{ // CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); // try // { // return Ok(this._userService.GetByLogINID(loginid, systemType)); // } // catch (Exception ex) // { // return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); // } //} //[HttpGet("loadMenu")] //[IgnoreAntiforgeryToken] //[ProducesErrorResponseType(typeof(Exception))] //public List loadMenu() //{ // SystemConfigarationService sysConfig = new SystemConfigarationService(); // return sysConfig.LoadMenu(); //} [HttpGet("getMenuesFromConfig")] public ActionResult getMenuesFromConfig() { List items = new List(); try { items = this._systemConfig.getMenuesFromConfig(); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpGet("getRole/{roleID}")] public ActionResult getRole(int roleID) { Role items = null; try { items = this._roleService.Get(roleID); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpGet("getAllRoles")] public ActionResult getAllRoles() { List items = new List(); try { items = this._roleService.GetAllRole(); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpPost("saveRole")] public ActionResult SaveRole(Role role) { int id = 0; CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); if (role.IsNew == true) { role.CreatedBy = currentUser.UserID; role.CreatedDate = DateTime.Now; } else { role.ModifiedBy = currentUser.UserID; role.ModifiedDate = DateTime.Now; } role.RoleStatus = EnumAuthStatus.Approved; role.ApproveDate = DateTime.Today; role.ApproveBy = currentUser.UserID; try { id = this._roleService.Save(role); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(id); } [HttpPost("GetEmpUserRole")] public ActionResult GetEmpUserRole(List searchEmps) { List ouroles = new List(); try { ouroles = this._userRoleService.Get(searchEmps); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(ouroles); } [HttpGet("getUserRoles/{roleType}/{userID}/{roleid}")] public ActionResult getUserRoles(EnumRoleType roletype, string userID, string roleid) { List items = new List(); int? nuserid = GlobalFunctions.GetApiDefaultIntData(userID); int? nroleid = GlobalFunctions.GetApiDefaultIntData(roleid); try { items = this._userRoleService.Get(roletype, nuserid, nroleid); // employee Name, Login-Status, status1, statu2, statu3 // employee group // status group //var results = items.GroupBy(n => new { n.UserID }).Select(g => new { g.Key.UserID }); //List newItems = new List(); //foreach (var item in results) //{ // var uItems = items.FindAll(x => x.UserID == item.UserID); // UserRole newItem = new UserRole(); // newItem.UserID = item.UserID; // newItem.userNameView = uItems[0].userNameView; // newItem.loginIDView = uItems[0].loginIDView; // string roles = ""; // uItems.ForEach(x => { roles = roles + x.roleNameView + ", "; }); // roles.Substring(0, roles.Length - 2); // newItem.roleNameView = roles; // newItems.Add(newItem); //} //items = newItems; } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpGet("GetRolePermissionbyUserID")] public ActionResult GetRolePermissionbyUserID() { List items = new List(); CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); try { items = this._roleService.GetRolePermissionbyUserID(currentUser.UserID); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpGet("GetAllPayrollTypes")] public ActionResult GetAllPayrollTypes() { List items = new List(); try { items = this._payrollTypeService.Get(); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpPost("saveUserRole")] public ActionResult saveUserRole(List userRoles) { CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); userRoles.ForEach(x => { if (x.payrollTypeID == 0 || x.payrollTypeID == null) { x.payrollTypeID = currentUser.PayrollTypeID; } }); userRoles.ForEach(userRole => { if (userRole.IsNew == true) { userRole.CreatedBy = currentUser.UserID; userRole.CreatedDate = DateTime.Now; } else { userRole.ModifiedBy = currentUser.UserID; userRole.ModifiedDate = DateTime.Now; userRole.UserRoleStatus = EnumAuthStatus.Approved; } userRole.AuthorizedDate = DateTime.Today; userRole.AuthorizedBy = currentUser.UserID; }); try { this._userRoleService.Save(userRoles, currentUser.UserID); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(); } [HttpGet("GetUserAccessType/{userid}")] public ActionResult GetUserAccessType(int userid) { List items = new List(); try { items = this._userAccessTypeService.GetByUserID(userid); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(items); } [HttpPost("SaveUserAccessType")] public ActionResult SaveUserAccessType(List userAccessTypes) { try { CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); userAccessTypes.ForEach(x => { x.CreatedBy = currentUser.UserID; x.CreatedDate = DateTime.Today; x.ApprovedBy = currentUser.UserID; x.ApprovedDate = DateTime.Today; }); this._userAccessTypeService.Save(userAccessTypes); } catch (Exception e) { return StatusCode(StatusCodes.Status500InternalServerError, e.Message); } return Ok(true); } // password history [HttpGet] [Route("getPasswordHistoryList")] [AllowAnonymous] public ActionResult GetPasswordHistoryList() { List items = new List(); CurrentUser user = CurrentUser.GetCurrentUser(HttpContext.User); int userId = user.UserID; try { items = _passwordHistoryService.Get(userId); } catch (Exception ex) { //return ex; return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } return Ok(items); } //[HttpPost("changePasswordbyAdmin")] //public ActionResult changePasswordbyAdmin(dynamic data) //{ // List passwordHistories = new List(); // User user = new User(); // CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); // user = new User(); // try // { // var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); // int userid = (int) item["userid"].ToObject(); // User ou = this._userService.Get(userid); // string newPassword = (string) item["newPassword"].ToObject(); // string email = (string) item["empEmail"].ToObject(); // string loginID = (string) item["loginid"].ToObject(); // // populate user // string tempPass = ou.Password; // user.ID = userid; // user.Password = // Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", newPassword.Trim()); // user.PasswordHints = newPassword; // user.LastPasswordChangedDate = DateTime.Today; // user.ChangePasswordAtNextLogon = true; // user.LoginID = loginID; // _userService.ChangePasswordAdmin(user); // PasswordHistory history = new PasswordHistory(); // history.UserID = user.ID; // history.UserPassword = // ou.Password; // Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", tempPass.Trim()); // history.CreatedBy = user.ID; // history.CreatedDate = DateTime.Today; // _passwordHistoryService.Save(history); // if (email != "") // { // EmailSettings emailSettings = _emailSettings.Value; // string password = newPassword.Trim(); // MailSender mailSender = new MailSender(); // mailSender.AddTo(email); // mailSender.Subject = "Your HR software Login Password has changed by Admin"; // mailSender.Body = @"Your HR software Login Password has changed by Admin. //

User Log-in ID : " + loginID + "

"; // mailSender.Body += "

New Password : " + newPassword.Trim() + "

"; // mailSender.ThreadSendMail(emailSettings); // } // } // catch (Exception e) // { // return StatusCode(StatusCodes.Status500InternalServerError, e.Message); // } // return Ok(true); //} // password change //[HttpPost("changePassword")] //public ActionResult ChangePassword(dynamic data) //{ // List passwordHistories = new List(); // bool temp = false; // User user = new User(); // CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); // string loginID = currentUser.LoginID; // int userId = currentUser.UserID; // user = _userService.Get(userId); // try // { // passwordHistories = _passwordHistoryService.Get(userId); // var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); // string oldPassword = (string) item["oldPassword"].ToObject(); // string newPassword = (string) item["newPassword"].ToObject(); // string confirmPassword = (string) item["confirmedPassword"].ToObject(); // if (user.Password != // Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", oldPassword.Trim())) // { // throw new Exception("Current/existing Password is not valid"); // } // // populate user // string tempPass = user.Password; // user.Password = newPassword; // user.UserName = currentUser.UserName; // user.PasswordHints = newPassword; // user.LastPasswordChangedDate = DateTime.Today; // user.ChangePasswordAtNextLogon = false; // user.LoginID = loginID; // //if (passwordHistories != null && passwordHistories.Count > 0 && // // confirmPassword.Trim() == user.Password.Trim()) // //{ // // PasswordHistory passwordHistory = passwordHistories.Find(x => // // x.UserPassword == // // Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", oldPassword.Trim())); // // temp = passwordHistory != null; // //} // //else // //{ // // temp = false; // //} // //if (temp) // //{ // // return Ok("Error Happened"); // //} // _userService.Save(user); // PasswordHistory history = new PasswordHistory(); // history.UserID = user.ID; // history.UserPassword = // Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", tempPass.Trim()); // history.CreatedBy = user.ID; // history.CreatedDate = DateTime.Today; // _passwordHistoryService.Save(history); // } // catch (Exception e) // { // return StatusCode(StatusCodes.Status500InternalServerError, e.Message); // } // return Ok(true); //} //[HttpPost("forgotPassword")] //[AllowAnonymous] //public ActionResult ForgotPassword(dynamic data) //{ // try // { // EmailSettings emailSettings = _emailSettings.Value; // var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); // string employeeId = (string) item["employeeId"].ToObject(); // string emailAddress = (string) item["emailAddress"].ToObject(); // User user = _userService.GetByLogINID(employeeId, EnumSystemType.Self_Service); // if (user == null) // { // // error message // return Ok(); // } // string password = Ease.NetCore.Utility.Global.CipherFunctions.Decrypt("CeLiMiTeD.AdMIn", user.Password); // MailSender mailSender = new MailSender(); // mailSender.AddTo(emailAddress); // mailSender.Subject = "Your HR software Login Password (Do not replay this mail)"; // mailSender.Body = "

User Log-in ID : " + employeeId + "

"; // mailSender.Body += "

Password : " + password + "

"; // mailSender.SendMail(emailSettings); // System.Threading.Thread.Sleep(500); // } // catch (Exception e) // { // return StatusCode(StatusCodes.Status500InternalServerError, e.Message); // } // return Ok(); //} [HttpGet] [Route("getVersionNumber")] public ActionResult getVersionNumber() { string connectionString = _config.GetSection("VersionNumber").Value; return Ok(connectionString); } [HttpPost] [AllowAnonymous] [Route("register")] public ActionResult RegisterUser(ErJobUser item) { try { item.Password = Ease.Core.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", item.Password); item.UserFrom = EnumUserFrom.SystemUser; item.IsActive = true; var isExist = _erJobUserService.CheckEmailMobExist(item.Email, item.Mobile); if (isExist != null) { throw new Exception("email or mobile no already exist"); } else { _erJobUserService.Save(item); } } catch (Exception ex) { return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } return Ok(); } [HttpPost("loginWithGoogle")] [AllowAnonymous] public async Task LoginWithGoogle([FromBody] string credentials) { //var hostName = Dns.GetHostEntry(HttpContext.Connection.RemoteIpAddress).HostName; var settings = new GoogleJsonWebSignature.ValidationSettings() { Audience = new List { this.GoogleClientId } }; var payload = await GoogleJsonWebSignature.ValidateAsync(credentials, settings); var userFromRepo = _erJobUserService.Get(payload.Email.ToLower()); var key = Encoding.ASCII.GetBytes(this.Secret); if (userFromRepo == null) { // return BadRequest("Login ID/Password is invalid"); ErJobUser user = new ErJobUser(); user.UserName = payload.Name; user.Email = payload.Email; user.UserFrom = EnumUserFrom.Google; user.IsActive = true; user.InActiveDate = null; user.InActiveReason = null; _erJobUserService.Save(user); userFromRepo = user; } //jwt var tokenHandler = new JwtSecurityTokenHandler(); var claims = new[] { new Claim("UserID", userFromRepo.ID.ToString()), new Claim("Email", userFromRepo.Email), new Claim("UserName", userFromRepo.UserName), new Claim("UserFrom", ((EnumUserFrom) userFromRepo.UserFrom).ToString()), new Claim("IsCVCompleted", userFromRepo.IsCVCompleted.ToString()) }; var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var token = tokenHandler.CreateToken(tokenDescriptor); string userToken = tokenHandler.WriteToken(token); if (userToken != null) { HttpContext.Session.SetString("EJWToken", userToken); } return Ok(userToken); } [HttpPost("login")] [AllowAnonymous] public IActionResult Login(dynamic data) { ErJobUser userFromRepo = null; var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); string userName = (string) item["loginID"].ToObject(); string password = (string) item["password"].ToObject(); userFromRepo = _erJobUserService.GetByLoginIDAndPassword(userName.ToLower(), password); if (userFromRepo == null) return BadRequest("Login ID/Password is invalid"); //jwt var key = Encoding.ASCII.GetBytes(this.Secret); var tokenHandler = new JwtSecurityTokenHandler(); var claims = new[] { new Claim("UserID", userFromRepo.ID.ToString()), new Claim("Email", userFromRepo.Email), new Claim("UserName", userFromRepo.UserName), new Claim("UserFrom", ((EnumUserFrom) userFromRepo.UserFrom).ToString()), new Claim("IsCVCompleted", userFromRepo.IsCVCompleted.ToString()) }; var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var token = tokenHandler.CreateToken(tokenDescriptor); string userToken = tokenHandler.WriteToken(token); if (userToken != null) { HttpContext.Session.SetString("EJWToken", userToken); } return Ok(userToken); } //[HttpPost] //public async Task Facebook([FromBody] string model) //{ // // 1.generate an app access token // var httpClient = new HttpClient { BaseAddress = new Uri("https://graph.facebook.com/debug_token?input_token={model}&access_token={appAccessToken.AccessToken}") }; // var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials"); // var appAccessToken = JsonConvert.DeserializeObject(appAccessTokenResponse); // // 2. validate the user access token // var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}"); // var userAccessTokenValidation = JsonConvert.DeserializeObject(userAccessTokenValidationResponse); // if (!userAccessTokenValidation.Data.IsValid) // { // return BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid facebook token.", ModelState)); // } // // 3. we've got a valid token so we can request user data from fb // var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}"); // var userInfo = JsonConvert.DeserializeObject(userInfoResponse); // // 4. ready to create the local user account (if necessary) and jwt // var user = await _userManager.FindByEmailAsync(userInfo.Email); // if (user == null) // { // var appUser = new AppUser // { // FirstName = userInfo.FirstName, // LastName = userInfo.LastName, // FacebookId = userInfo.Id, // Email = userInfo.Email, // UserName = userInfo.Email, // PictureUrl = userInfo.Picture.Data.Url // }; // var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); // if (!result.Succeeded) return new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)); // await _appDbContext.Customers.AddAsync(new Customer { IdentityId = appUser.Id, Location = "", Locale = userInfo.Locale, Gender = userInfo.Gender }); // await _appDbContext.SaveChangesAsync(); // } // // generate the jwt for the local user... // var localUser = await _userManager.FindByNameAsync(userInfo.Email); // if (localUser == null) // { // return BadRequest(Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)); // } // var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id), _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }); // return new OkObjectResult(jwt); //} // } //private void CheckAuthorization() //{ // string app_id = "**************"; // string app_secret = "************************"; // if (Request["code"] == null) // { // var redirectUrl = string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", app_id, Request.Url.AbsoluteUri); // Response.Redirect(redirectUrl); // } // else // { // AccessUser au = new AccessUser(); // string url = string.Format("https://graph.facebook.com/v3.2/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", app_id, Request.Url.AbsoluteUri, app_secret, Request["code"].ToString()); // HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // { // StreamReader reader = new StreamReader(response.GetResponseStream()); // string vals = reader.ReadToEnd(); // au = JsonConvert.DeserializeObject(vals); // string token = au.access_token; // } // } //} } }