Beispiel #1
0
        public async Task<HttpResponseMessage> UpdateUser(UserModel model)
        {
            List<string> errors = new List<string>();
            bool error = false;
            if (string.IsNullOrEmpty(model.Username))
            {
                errors.Add("Email is required");
                error = true;
            }
            if (string.IsNullOrEmpty(model.Zipcode))
            {
                errors.Add("Zipcode is required");
                error = true;
            }

            if (error)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, errors.ToArray());
            }

            var user = await UserManager.FindByNameAsync(User.Identity.Name);
            user.Email = model.Email;
            if (user.Email.ToLower() != model.Email.ToLower())
            {
                user.EmailConfirmed = false;
            }
            if (user.PhoneNumber != model.PhoneNumber || string.IsNullOrEmpty(model.PhoneNumber))
            {
                user.PhoneNumberConfirmed = false;
            }
            user.UserName = model.Username ?? model.Email;
            user.Zipcode = model.Zipcode;
            user.FirstName = model.FirstName;
            user.LastName = model.LastName;
            user.PhoneNumber = model.PhoneNumber;
            user.Birthday = model.Birthday;
            user.UpdatedAt = DateTimeOffset.UtcNow;

            IdentityResult result = await this.UserManager.UpdateAsync(user);
            if (!result.Succeeded)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, result.Errors);
            }
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }
Beispiel #2
0
        public async Task<HttpResponseMessage> RegisterUser(UserModel model)
        {
            var user = await UserManager.FindByGuidAsync(model.Guid);
            if (user != null)
            {
                // Guid is already attached to a registered user -- so create a fresh user
                if (!string.IsNullOrWhiteSpace(user.PasswordHash))
                {
                    //return Request.CreateResponse(HttpStatusCode.BadRequest, new List<string>(){"Email is already registered."});
                    var guid = System.Guid.NewGuid().ToString();
                    var idresult = await UserManager.CreateAsync(new User
                    {
                        Email = model.Email,
                        UserName = model.Username ?? model.Email,
                        Guid = guid,
                        Zipcode = model.Zipcode,
                        PatientInfo = new PatientInfo(),
                        Wallet = new Wallet(),
                        CreatedAt = DateTimeOffset.UtcNow,
                        UpdatedAt = DateTimeOffset.UtcNow,
                        LastLogin = DateTimeOffset.UtcNow
                    }, model.Password);
                    if (!idresult.Succeeded)
                    {
                        return Request.CreateResponse(HttpStatusCode.BadRequest, idresult.Errors);
                    }
                }
                else // Update the existing anonymous user with registration info
                {
                    try
                    {
                        //var passwordResult = await UserManager.AddPasswordAsync(user.Id, model.Password);
                        //if (!passwordResult.Succeeded)
                        //{
                        //    return Request.CreateResponse(HttpStatusCode.BadRequest, passwordResult.Errors);
                        //}

                        user.Email = model.Email;
                        user.UserName = model.Username ?? model.Email;
                        user.Wallet = new Wallet();
                        user.UpdatedAt = DateTimeOffset.UtcNow;
                        user.LastLogin = DateTimeOffset.UtcNow;
                        IdentityResult result = await this.UserManager.UpdateAsync(user);
                        if (!result.Succeeded)
                        {
                            return Request.CreateResponse(HttpStatusCode.BadRequest, result.Errors);
                        }
                    }
                    catch { }
                }
            }
            else
            {
                _logger.ErrorFormat("Registration error should not hit user guid {0} and email {1}", model.Guid, model.Email);
                return Request.CreateResponse(HttpStatusCode.BadRequest, new List<string>()
                {
                    "Registration is not valid. Clear your cookies and try again."
                });
            }
            user = await UserManager.FindByEmailAsync(model.Email);
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));

            //await UserManager.SendEmailAsync(user.Id,
            //    "Confirm your account",
            //    "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            await SendVerificationEmail(model.Email,
                 "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>", "E-mail confirmation");

            string patientListId = ConfigurationManager.AppSettings["MailChimpPatientListId"];
            AddEmailToMailChimp(model.Username ?? model.Email, model.FirstName, model.LastName, patientListId);

            // Auto login after register (successful user registration should return access_token)
            var loginResult = this.Login(new UserModel() { Password = model.Password, ConfirmPassword = model.Password, Username = model.Email, Email = model.Email, Guid = user.Guid });
            return await loginResult;
        }
Beispiel #3
0
        public async Task<HttpResponseMessage> Login(UserModel login)
        {
            //var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
            //var message = new MailMessage();
            //message.To.Add(new MailAddress("*****@*****.**"));  // replace with valid value 
            //message.From = new MailAddress("*****@*****.**");  // replace with valid value
            //message.Subject = "Your email subject";
            //message.Body = string.Format(body, "AskMJane", "*****@*****.**", "hi");
            //message.IsBodyHtml = true;

            //using (var smtp = new SmtpClient())
            //{
            //    var credential = new NetworkCredential
            //    {
            //        UserName = "******", // replace with valid value
            //        Password = "******" // replace with valid value
            //    };
            //    smtp.Credentials = credential;
            //    smtp.Host = "smtp-mail.outlook.com";
            //    smtp.Port = 587;
            //    smtp.EnableSsl = true;
            //    await smtp.SendMailAsync(message);

            //}

            var request = HttpContext.Current.Request;
            var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "token";
            _logger.DebugFormat("{0} {1} {2} {3}", tokenServiceUrl, request.Url, request.Url.GetLeftPart(UriPartial.Authority), request.ApplicationPath);
            using (var client = new HttpClient())
            {
                var requestParams = new List<KeyValuePair<string, string>>
            {
               // new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", login.Username ?? login.Email),
                //new KeyValuePair<string, string>("password", login.Password)
            };
                var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
                _logger.DebugFormat("{0} {1} {2} {3}", tokenServiceUrl, requestParams[0], requestParams[1], requestParams[2]);
                var tokenServiceResponse = await client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded);
                var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();
                var responseCode = tokenServiceResponse.StatusCode;
                _logger.DebugFormat("{0} {1}", responseString, responseCode);
                var responseObj = JObject.Parse(responseString);

                if (responseCode == HttpStatusCode.OK)
                {
                    try
                    {
                        User user = null;
                        if (login.Email != null && !login.Email.IsNullOrWhiteSpace())
                        {
                            user =
                                await
                                    HGContext.Users.Include("UserSessions")
                                        .FirstOrDefaultAsync(x => x.Email == login.Email);
                        }
                        else
                        {
                            user =
                                await
                                    HGContext.Users.Include("UserSessions")
                                        .FirstOrDefaultAsync(x => x.UserName == login.Username);
                        }

                        if (await UserManager.IsInRoleAsync(user.Id, Role.DispensaryManager))
                        {
                            return Request.CreateResponse(HttpStatusCode.BadRequest, new List<string> { "You seems to be a dispensary manager, try to login from dispensary login screen." });
                        }


                        responseObj["usertoken"] = user.Guid;
                        var sessiontoken = Guid.NewGuid().ToString();
                        user.UserSessions.Add(new UserSession()
                        {
                            Session = new Session()
                            {
                                LastSeen = DateTimeOffset.UtcNow,
                                Token = sessiontoken
                            },
                            UserId = user.Id
                        });
                        var result = await HGContext.SaveChangesAsync();
                        if (result == 0)
                        {
                            _logger.ErrorFormat("Login:  Create Session failed --  UserId: {0} Guid: {1}", user.Id,
                                user.Guid);
                            return Request.CreateResponse(HttpStatusCode.BadRequest);
                        }
                        responseObj["sessiontoken"] = sessiontoken;
                        var anonuser = await HGContext.Users.FirstOrDefaultAsync(x => x.Guid == login.Guid);
                        if (user.Id != anonuser.Id && string.IsNullOrWhiteSpace(anonuser.PasswordHash))
                        {
                            var cart = await HGContext.Orders.FirstOrDefaultAsync(x =>
                                x.UserId == user.Id && x.IsCheckedOut == false &&
                                x.DispensaryProductVariantOrders.Count > 0);
                            //Set Anonymous user cart to user cart
                            var anoncart = await HGContext.Orders.FirstOrDefaultAsync(x => x.UserId == anonuser.Id
                                                                                           && x.IsCheckedOut == false &&
                                                                                           x.DispensaryProductVariantOrders.Count > 0);
                            if (anoncart != null)
                            {
                                anoncart.UserId = user.Id;
                                anoncart.UpdatedAt = DateTimeOffset.UtcNow;
                                var cartresult = await HGContext.SaveChangesAsync();
                                if (cartresult == 0)
                                {
                                    _logger.ErrorFormat(
                                        "Login:  Anonymous Cart swap failed -- CartId: {2} UserId: {0} Guid: {1}",
                                        anonuser.Id, anonuser.Guid, anoncart.Id);
                                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                                }
                            }


                            HGContext.Users.Remove(anonuser);
                            var anonuserresult = await HGContext.SaveChangesAsync();
                            if (anonuserresult == 0)
                            {
                                _logger.ErrorFormat("Login:  Anonymous User removal failed -- Id: {0} Guid: {1}",
                                    anonuser.Id, anonuser.Guid);

                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.ErrorFormat("Login error {0}", e);
                    }


                }
                else
                {
                    var error = new List<string>() { "The username or password is incorrect." };
                    return Request.CreateResponse(responseCode, error);
                }

                var response = Request.CreateResponse(responseCode, responseObj);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }
        }
        public async Task<HttpResponseMessage> Login(UserModel login)
        {
            var email = string.IsNullOrEmpty(login.Email) ? login.Username : login.Email;
            var dispensary =
                await
                    HGContext.PendingDispensaries.Include(d => d.Address).SingleOrDefaultAsync(
                        d =>
                            d.Email.ToLower() == email.ToLower() &&
                            d.PendingDispensaryStatus == PendingDispensaryStatus.WaitingForApprove);
            if (dispensary != null)
            {
                var result = UserManager.PasswordHasher.VerifyHashedPassword(dispensary.Password, login.Password);
                if (result == PasswordVerificationResult.Success)
                {
                    return Request.CreateResponse(HttpStatusCode.OK, dispensary);
                }
            }


            var request = HttpContext.Current.Request;
            var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "token";
            _logger.DebugFormat("{0} {1} {2} {3}", tokenServiceUrl, request.Url, request.Url.GetLeftPart(UriPartial.Authority), request.ApplicationPath);
            using (var client = new HttpClient())
            {
                var requestParams = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", login.Username ?? login.Email),
                new KeyValuePair<string, string>("password", login.Password)
            };
                var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
                _logger.DebugFormat("{0} {1} {2} {3}", tokenServiceUrl, requestParams[0], requestParams[1], requestParams[2]);
                var tokenServiceResponse = await client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded);
                var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();
                var responseCode = tokenServiceResponse.StatusCode;
                _logger.DebugFormat("{0} {1}", responseString, responseCode);
                var responseObj = JObject.Parse(responseString);

                if (responseCode == HttpStatusCode.OK)
                {
                    try
                    {
                        User user = null;
                        if (login.Email != null && !login.Email.IsNullOrWhiteSpace())
                        {
                            user =
                                await
                                    HGContext.Users.Include("UserSessions")
                                        .FirstOrDefaultAsync(x => x.Email == login.Email);
                        }
                        else
                        {
                            user =
                                await
                                    HGContext.Users.Include("UserSessions")
                                        .FirstOrDefaultAsync(x => x.UserName == login.Username);
                        }

                        if (!await UserManager.IsInRoleAsync(user.Id, Role.DispensaryManager))
                        {
                            return Request.CreateResponse(HttpStatusCode.BadRequest, new List<string> { "You seems to be a regular user, please login from regular login screen" });
                        }

                        responseObj["usertoken"] = user.Guid;
                        var sessiontoken = Guid.NewGuid().ToString();
                        user.UserSessions.Add(new UserSession()
                        {
                            Session = new Session()
                            {
                                LastSeen = DateTimeOffset.UtcNow,
                                Token = sessiontoken
                            },
                            UserId = user.Id
                        });
                        var result = await HGContext.SaveChangesAsync();
                        if (result == 0)
                        {
                            _logger.ErrorFormat("Login:  Create Session failed --  UserId: {0} Guid: {1}", user.Id,
                                user.Guid);
                            return Request.CreateResponse(HttpStatusCode.BadRequest);
                        }
                        responseObj["sessiontoken"] = sessiontoken;
                        var anonuser = await HGContext.Users.FirstOrDefaultAsync(x => x.Guid == login.Guid);
                        if (user.Id != anonuser.Id && string.IsNullOrWhiteSpace(anonuser.PasswordHash))
                        {
                            var cart = await HGContext.Orders.FirstOrDefaultAsync(x =>
                                x.UserId == user.Id && x.IsCheckedOut == false &&
                                x.DispensaryProductVariantOrders.Count > 0);
                            //Set Anonymous user cart to user cart
                            var anoncart = await HGContext.Orders.FirstOrDefaultAsync(x => x.UserId == anonuser.Id
                                                                                           && x.IsCheckedOut == false &&
                                                                                           x
                                                                                               .DispensaryProductVariantOrders
                                                                                               .Count > 0);
                            if (anoncart != null)
                            {
                                anoncart.UserId = user.Id;
                                anoncart.UpdatedAt = DateTimeOffset.UtcNow;
                                var cartresult = await HGContext.SaveChangesAsync();
                                if (cartresult == 0)
                                {
                                    _logger.ErrorFormat(
                                        "Login:  Anonymous Cart swap failed -- CartId: {2} UserId: {0} Guid: {1}",
                                        anonuser.Id, anonuser.Guid, anoncart.Id);
                                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                                }
                            }


                            HGContext.Users.Remove(anonuser);
                            var anonuserresult = await HGContext.SaveChangesAsync();
                            if (anonuserresult == 0)
                            {
                                _logger.ErrorFormat("Login:  Anonymous User removal failed -- Id: {0} Guid: {1}",
                                    anonuser.Id, anonuser.Guid);

                            }
                        }

                        if (await UserManager.IsInRoleAsync(user.Id, Role.DispensaryManager))
                        {
                            if (
                                !await
                                    HGContext.Dispensaries.AnyAsync(
                                        d => d.EmailAddress.ToLower() == user.Email.ToLower()))
                            {
                                responseObj.Add("notCompleted", true);
                            }
                            else
                            {
                                responseObj.Add("notCompleted", false);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.ErrorFormat("Login error {0}", e);
                    }


                }
                else
                {
                    var error = new List<string>() { "The username or password is incorrect." };
                    return Request.CreateResponse(responseCode, error);
                }

                var response = Request.CreateResponse(responseCode, responseObj);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }
        }