Пример #1
0
        public async Task <IActionResult> Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrors()));
            }

            ApplicationUser user = new ApplicationUser
            {
                Email         = model.Email,
                SecurityStamp = Guid.NewGuid().ToString(),
                UserName      = model.UserName,
                Name          = model.UserName,
                NameEn        = model.UserName,
                Gender        = model.Gender,
                PhoneNumber   = model.PhoneNumber,
                FbId          = model.FbId,
                ProfileImg    = "http://graph.facebook.com/" + model.FbId + "/picture?type=large"
            };
            var result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                string Temp = result.Errors.Select(s => s.Code).FirstOrDefault();
                if (Temp == "DuplicateUserName")
                {
                    return(BadRequest("هذا المستخدم موجود من قبل ."));
                }
                else
                {
                    return(BadRequest(result.Errors.Select(s => s.Description)));
                }
            }


            if (model.IsLawyer)
            {
                var id = lawyerService.InsertLawyer(new LawyerDTO {
                    UserId = user.Id, Name = user.UserName
                });
                user.LawyerId = id;
                await UserManager.UpdateAsync(user);

                await UserManager.AddToRoleAsync(user, "Lawyer");

                //var lawyer = lawyerService.GetLawyerByUserId(user.Id);
                //lawyer.ProfileImg = "http://graph.facebook.com/" + user.FbId + "/picture?type=large";
                //lawyerService.UpdateLawyer(lawyer);
            }
            else
            {
                await UserManager.AddToRoleAsync(user, "User");
            }

            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Action(
                "ConfirmEmail",
                "Account",
                values: new { userId = user.Id, code = code },
                protocol: Request.Scheme);

            if (string.IsNullOrWhiteSpace(model.FbId))
            {
                //await emailSender.Send(user.Email, "Confirm your email",
                //$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");


                //var msg = IsLTR ? "Email confirmation has been sent to your email."
                //    : "تم إرسال رسالة تأكيد بالبريد الإلكتروني إلى بريدك الإلكتروني.";

                //return Ok(new { Message = msg });

                var msg = IsLTR ? "Registered on system."
                                                : "تم تسجيلك بنجاح.";
                user.EmailConfirmed = true;
                var result1 = await UserManager.UpdateAsync(user);


                string apiUrl = $"http://{Request.Host}/api/Auth/Token";
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    var bodyJS = JsonConvert.SerializeObject(new LoginModel {
                        UserName = model.Email, Password = model.Password
                    });
                    var body = new StringContent(bodyJS, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(apiUrl, body);

                    if (response.IsSuccessStatusCode)
                    {
                        var data = await response.Content.ReadAsStringAsync();

                        var result2 = Newtonsoft.Json.JsonConvert.DeserializeObject <TokenViewModel>(data);
                        result2.Message = msg;
                        //HttpContext.Session.SetString("token", result.token);
                        WriteCookies("token", result2.token, result2.expiration);
                        WriteCookies("IsLawyer", result2.IsLawyer.ToString(), result2.expiration);
                        WriteCookies("UserName", result2.UserName, result2.expiration);
                        WriteCookies("UserNameEn", result2.UserNameEn, result2.expiration);
                        return(Ok(result2));
                    }
                }


                return(Ok(new { Message = msg }));
            }
            else
            {
                var msg = IsLTR ? "Registered on system."
                    : "تم تسجيلك بنجاح.";
                user.EmailConfirmed = true;
                var result1 = await UserManager.UpdateAsync(user);


                string apiUrl = $"http://{Request.Host}/api/Auth/Token";
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    var bodyJS = JsonConvert.SerializeObject(new LoginModel {
                        UserName = model.Email, Password = model.Password
                    });
                    var body = new StringContent(bodyJS, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(apiUrl, body);

                    if (response.IsSuccessStatusCode)
                    {
                        var data = await response.Content.ReadAsStringAsync();

                        var result2 = Newtonsoft.Json.JsonConvert.DeserializeObject <TokenViewModel>(data);
                        result2.Message = msg;
                        //HttpContext.Session.SetString("token", result.token);
                        WriteCookies("token", result2.token, result2.expiration);
                        WriteCookies("IsLawyer", result2.IsLawyer.ToString(), result2.expiration);
                        WriteCookies("UserName", result2.UserName, result2.expiration);
                        WriteCookies("UserNameEn", result2.UserNameEn, result2.expiration);
                        return(Ok(result2));
                    }
                }


                return(Ok(new { Message = msg }));
            }
        }