public string RegisterByEmail(string email)
        {
            var result = RequestCredentials(email);

            if (!string.IsNullOrEmpty(result))
            {
                RegistrationResponse response = JsonConvert.DeserializeObject <RegistrationResponse>(result);

                if (response == null)
                {
                    throw new Exception("Service temporarily unavailable. Please register through account website.");
                }

                if (response.ReturnCode == 0)
                {
                    if (response.Dto.ApplicationIds.ContainsKey(RegistrationConfig.BOLT_SERVICE_ID))
                    {
                        return(response.Dto.ApplicationIds[RegistrationConfig.BOLT_SERVICE_ID]);
                    }
                }
                else if (response.ReturnCode == 8)
                {
                    throw new Exception(string.Format("Error: User Already exists. Please use another email or get a valid AppId from Photon dashboard."));
                }

                throw new Exception(string.Format("Error {0}: {1}", response.ReturnCode, response.Message));
            }

            throw new Exception("Server's response was empty. Please register through account website during this service interruption.");
        }
        /// <summary>
        /// Add User Details into the database
        /// </summary>
        /// <param name="userDetails">User Registration Request</param>
        /// <returns>If data added successully, return response data else null or exception</returns>
        public async Task <RegistrationResponse> UserRegistration(RegistrationRequest userDetails)
        {
            try
            {
                RegistrationResponse responseData = null;
                SQLConnection();
                using (SqlCommand cmd = new SqlCommand("AddUserDetails", conn))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@FirstName", userDetails.FirstName);
                    cmd.Parameters.AddWithValue("@LastName", userDetails.LastName);
                    cmd.Parameters.AddWithValue("@Email", userDetails.Email);
                    cmd.Parameters.AddWithValue("@Password", userDetails.Password);
                    cmd.Parameters.AddWithValue("@IsActive", true);
                    cmd.Parameters.AddWithValue("@UserRole", _user);
                    cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now);
                    cmd.Parameters.AddWithValue("@ModifiedDate", DateTime.Now);

                    conn.Open();
                    SqlDataReader dataReader = await cmd.ExecuteReaderAsync();

                    responseData = RegistrationResponseModel(dataReader);
                };
                return(responseData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #3
0
        public ProfileDTO BuildProfileDTO(RegistrationResponse data)
        {
            ProfileDTO result = new ProfileDTO()
            {
                About            = data.About,
                MySports         = data.MySports,
                Children         = data.Children,
                Id               = data.Id,
                Type             = data.Type,
                FirstName        = data.FirstName,
                LastName         = data.LastName,
                DisplayName      = data.DisplayName,
                ShortId          = data.ShortId,
                DateOfBirth      = data.DateOfBirth,
                Availability     = data.Availability,
                LastSeen         = data.LastSeen,
                ParentId         = data.ParentId,
                ChildUserName    = data.ChildUserName,
                ChildPassword    = data.ChildPassword,
                Contact          = data.Contact,
                Address          = data.Address,
                BackgroundImage  = data.BackgroundImage,
                Avatar           = data.Avatar,
                BrandImage       = data.BrandImage,
                Media            = data.Media,
                IsEmailConfirmed = data.IsEmailConfirmed
            };

            return(result);
        }
        /// <summary>
        /// Verify User Login Details
        /// </summary>
        /// <param name="loginDetails">Login Request</param>
        /// <returns>If data verified, return response data else null or exception</returns>
        public async Task <RegistrationResponse> UserLogin(LoginRequest loginDetails)
        {
            try
            {
                RegistrationResponse responseData = null;
                SQLConnection();
                using (SqlCommand cmd = new SqlCommand("ValidateLogin", conn))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Email", loginDetails.Email);
                    cmd.Parameters.AddWithValue("@Password", loginDetails.Password);
                    cmd.Parameters.AddWithValue("@UserRole", _user);

                    conn.Open();
                    SqlDataReader dataReader = await cmd.ExecuteReaderAsync();

                    responseData = RegistrationResponseModel(dataReader);
                };
                return(responseData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
 /// <summary>
 /// Registration Response Method
 /// </summary>
 /// <param name="dataReader">Sql Data Reader</param>
 /// <returns>It return Response Data or Exception</returns>
 private RegistrationResponse RegistrationResponseModel(SqlDataReader dataReader)
 {
     try
     {
         RegistrationResponse responseData = null;
         while (dataReader.Read())
         {
             responseData = new RegistrationResponse
             {
                 ID           = Convert.ToInt32(dataReader["ID"]),
                 FirstName    = dataReader["FirstName"].ToString(),
                 LastName     = dataReader["LastName"].ToString(),
                 Email        = dataReader["Email"].ToString(),
                 IsActive     = Convert.ToBoolean(dataReader["IsActive"]),
                 UserRole     = dataReader["UserRole"].ToString(),
                 CreatedDate  = Convert.ToDateTime(dataReader["CreatedDate"]),
                 ModifiedDate = Convert.ToDateTime(dataReader["ModifiedDate"])
             };
         }
         return(responseData);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
        /// <summary>
        /// Handles a response from the account server for a pending registration.
        /// </summary>
        /// <param name="response">Details of the registration response</param>
        public void OnAccountRegistrationResponse(RegistrationResponse response)
        {
            switch (response.Status)
            {
            case RegistrationStatusCode.Ok:
                newAccountForm.Close();
                MessageBox.Show("Your account has been successfully registered.");
                break;

            case RegistrationStatusCode.UsernameTaken:
                MessageBox.Show("The requested username is already taken. Please try again");
                break;

            case RegistrationStatusCode.WeakCredentials:
                MessageBox.Show("Double-check your username and email address.");
                break;

            case RegistrationStatusCode.ServerError:
                MessageBox.Show("Your request could not be processed. A server-side error has occured.");
                break;

            case RegistrationStatusCode.MalformedData:
                MessageBox.Show("An internal client error has occured. Your request could not be processed.");
                break;
            }
        }
        public async Task <IActionResult> VerifyDetails(string nid, string dob)
        {
            ViewBag.lang = langcode;
            if (!string.IsNullOrWhiteSpace(nid) && !string.IsNullOrWhiteSpace(dob))
            {
                try
                {
                    var result = ValidateIDByNIC(nid, "");
                    if (result == true)
                    {
                        //var dateTime = Convert.ToDateTime(dob);
                        //var date = dateTime.ToString("dd-MM-yyyy");
                        ClsInput clsInput = new ClsInput()
                        {
                            nationalID = nid, yearOfBirth = dob
                        };
                        _logger.LogInformation(_className + "::VerifyDetails::GetMemberByNationalId::START::" + clsInput.yearOfBirth);

                        RegistrationResponse res = await CustomerHandler.GetMemberByNationalId(clsInput);

                        _logger.LogInformation(_className + "::VerifyDetails::GetMemberByNationalId::Response::" + res.ResponseMessage);
                        if (res.Members != null && res.Members.Count > 0)
                        {
                            Registration _userdetails = new Registration();
                            _userdetails = res.Members.Where(c => c.MemberType == "EMPLOYEE").FirstOrDefault();
                            _logger.LogInformation(_className + "::VerifyDetails::GetMemberByNationalId::_userdetails::" + _userdetails.MemberName);
                            setsession(nid, dob, _userdetails.MemberMobileNo);
                            return(Json(new { success = true }));
                        }
                        else
                        {
                            var responseMessage = string.Empty;
                            if (res.Errors != null && res.Errors.Count > 0)
                            {
                                responseMessage = "Invalid National ID or Date of Birth.Please check again.";
                            }
                            else
                            {
                                responseMessage = res.ResponseMessage;
                            }
                            return(Json(new { success = false, responseText = responseMessage }));
                        }
                    }
                    else
                    {
                        return(Json(new { success = false, responseText = "Invalid Credentials." }));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogInformation(_className + "::VerifyDetails::" + ex.Message + "::InnerException::" + ex.InnerException?.Message);
                }
                return(View());
            }
            else
            {
                _logger.LogInformation(_className + "::VerifyDetails::nationalId is NULL");
                return(View());
            }
        }
Example #8
0
        public Response <RegistrationResponse> Login([FromBody] LoginAttempt login)
        {
            var service  = new Tete.Api.Services.Authentication.LoginService(this.context);
            var token    = HttpContext.Request.Cookies[Constants.SessionTokenName];
            var user     = service.GetUserVMFromToken(token);
            var response = new RegistrationResponse();

            if (user == null || (user != null && user.Roles.Contains("Guest")))
            {
                var session = service.Login(login);

                if (session != null)
                {
                    if (user != null)
                    {
                        service.DeleteAccount(user.UserId, user);
                    }

                    SetTokenCookie(session.Token);
                    response.Successful = true;
                }
                else
                {
                    response.Messages.Add("Invalid Login");
                    response.Successful = false;
                }
            }
            else
            {
                response.Messages.Add("You're already logged in!");
                response.Successful = false;
            }

            return(new Response <RegistrationResponse>(response));
        }
Example #9
0
        public Response <RegistrationResponse> Delete([FromBody] LoginAttempt login)
        {
            var response = new RegistrationResponse()
            {
                Successful = false
            };
            var service = new Tete.Api.Services.Authentication.LoginService(this.context);
            var token   = HttpContext.Request.Cookies[Constants.SessionTokenName];
            var user    = service.GetUserVMFromToken(token);
            var session = service.Login(login);
            var user2   = service.GetUserVMFromToken(session.Token);

            if (user != null && session != null && user2 != null && user.UserId == user2.UserId)
            {
                try
                {
                    service.DeleteAccount(user.UserId, user);
                    response.Successful = true;
                }
                catch { }
            }

            if (!response.Successful)
            {
                response.Messages.Add("Unable to delete account due to login issues.");
            }

            return(new Response <RegistrationResponse>(response));
        }
Example #10
0
        public async Task <ActionResult> Register(RegistrationViewModel registrationModel)
        {
            var model = new LoginViewModel(new SigninViewModel(registrationModel.ReturnUrl), registrationModel);

            if (!ModelState.IsValid)
            {
                return(View("Login", model));
            }

            if (await _clientAccountsRepository.IsTraderWithEmailExistsAsync(registrationModel.Email))
            {
                ModelState.AddModelError("", $"Email {registrationModel.Email} is already in use.");
                return(View("Login", model));
            }

            string userIp    = this.GetIp();
            string referer   = null;
            string userAgent = this.GetUserAgent();

            if (!string.IsNullOrEmpty(registrationModel.Referer))
            {
                referer = new Uri(registrationModel.Referer).Host;
            }

            RegistrationResponse result = await _registrationClient.RegisterAsync(new RegistrationModel
            {
                Email     = registrationModel.Email,
                Password  = PasswordKeepingUtils.GetClientHashedPwd(registrationModel.RegistrationPassword),
                Ip        = userIp,
                Changer   = RecordChanger.Client,
                UserAgent = userAgent,
                Referer   = referer
            });

            if (result == null)
            {
                ModelState.AddModelError("", "Technical problems during registration.");
                return(View("Login", model));
            }

            var clientAccount = new Core.Clients.ClientAccount
            {
                Id              = result.Account.Id,
                Email           = result.Account.Email,
                Registered      = result.Account.Registered,
                NotificationsId = result.Account.NotificationsId,
                Phone           = result.Account.Phone
            };

            foreach (var registrationConsumer in _registrationConsumers)
            {
                registrationConsumer.ConsumeRegistration(clientAccount, userIp, CultureInfo.CurrentCulture.Name);
            }

            var identity = await _userManager.CreateUserIdentityAsync(clientAccount.Id, clientAccount.Email, registrationModel.Email);

            await HttpContext.Authentication.SignInAsync("ServerCookie", new ClaimsPrincipal(identity), new AuthenticationProperties());

            return(RedirectToAction("PersonalInformation", "Profile", new { returnUrl = registrationModel.ReturnUrl }));
        }
Example #11
0
        public Response <RegistrationResponse> AdminDelete([FromBody] RoleUpdate login)
        {
            var response = new RegistrationResponse()
            {
                Successful = false
            };
            var service = new Tete.Api.Services.Authentication.LoginService(this.context);
            var token   = HttpContext.Request.Cookies[Constants.SessionTokenName];
            var user    = service.GetUserVMFromToken(token);

            if (user != null)
            {
                try
                {
                    service.DeleteAccount(login.UserId, user);
                    response.Successful = true;
                }
                catch { }
            }

            if (!response.Successful)
            {
                response.Messages.Add("Failed to delete account.");
            }

            return(new Response <RegistrationResponse>(response));
        }
Example #12
0
 /// <summary>
 /// Raises the register error event.
 /// </summary>
 /// <param name="response">Response.</param>
 private void OnRegisterError(RegistrationResponse response)
 {
     foreach (SparkView view in sparkViews)
     {
         view.SendEvent_RegisterError(response);
     }
 }
Example #13
0
        public async Task<RegistrationResponse> Post([FromBody] User user)
        {
            var resp = new RegistrationResponse { Success = false };
            try
            {
                if (!context.Users.Any(u => u.Email == user.Email))
                {
                    var emailValidator = new EmailAddressAttribute();

                    if (emailValidator.IsValid(user.Email) &&
                        !string.IsNullOrEmpty(user.Password) &&
                        !string.IsNullOrEmpty(user.UserName))
                       
                    {
                        user.Password = PasswordHash.HashPassword(user.Password);
                        await context.Users.AddAsync(user);
                        await context.SaveChangesAsync();
                        resp.UserName = user.UserName;
                        resp.Success = true;
                    }
                    else
                        resp.Message = "Strings cannot be empty";
                }
                else
                    resp.Message = "An account with this email already exists";
            }
            catch
            {
                resp.Message = "An internal error occurred. Please try again.";
            }

            return resp;
        }       
Example #14
0
        public async Task <RegistrationResponse> SignUp(List <RegistrationRequestItem> fields, CancellationTokenSource cancellationTokenSource)
        {
            await Task.Delay(1000);

            var resp = new RegistrationResponse()
            {
                Successful       = true,
                Error            = "",
                InvalidFieldsIds = new List <string>(),
                Token            = TOKEN
            };
            var email = fields.FirstOrDefault(p => p.Id == "1");

            if (email != null && email.Value.First() != 'a')
            {
                resp.Successful = false;
                resp.InvalidFieldsIds.Add("1");
                resp.Error += IsRussianCulture ? $"Поле с ID == 1 должно начинаться на \"a\"\n" : "E-mail should starts with \"a\" letter\n";
            }

            var password = fields.FirstOrDefault(p => p.Type == RegistrationFieldType.Password);

            if ((password?.Value?.Length ?? 0) < 6)
            {
                resp.Successful = false;
                resp.InvalidFieldsIds.Add(password.Id);
                resp.Error += IsRussianCulture ? $"Пароль должен быть не менее 6 символов\n" : "Password length couldn't be less than 6";
            }
            resp.Error = resp.Error?.Trim();

            return(resp);
        }
Example #15
0
        public RegistrationResponse TestRegistration(string userId)
        {
            var user = _userRepository.GetUserData(userId);

            if (user != null)
            {
                return(new RegistrationResponse
                {
                    PicUrl = user.PictureUrl,
                    NicknameDateOfChange = user.NicknameDateOfChange,
                    UserId = user.UserId,
                    UserNickname = user.UserNickname
                });
            }
            DateTimeOffset date    = DateTimeOffset.UtcNow;
            User           newUser = new User(userId, "", date);

            _userRepository.SaveUserData(newUser);

            RegistrationResponse toReturn = new RegistrationResponse
            {
                NicknameDateOfChange = date,
                PicUrl       = "",
                UserId       = userId,
                UserNickname = userId
            };

            return(toReturn);
        }
Example #16
0
        public async Task <RegistrationResult> RegisterAsync(string userName, string password)
        {
            RegistrationRequest  request  = new RegistrationRequest(userName, password);
            RegistrationResponse response = await communicationService.SendAsync(request) as RegistrationResponse;

            return(response.Result);
        }
Example #17
0
        public RegistrationResponse Registration(UserRegistrationRequest userDetails)
        {
            try
            {
                RegistrationResponse responseData = null;
                userDetails.Password = EncodeDecode.EncodePasswordToBase64(userDetails.Password);
                var userData = new Users
                {
                    FirstName    = userDetails.FirstName,
                    LastName     = userDetails.LastName,
                    Email        = userDetails.Email,
                    Password     = userDetails.Password,
                    IsActive     = true,
                    UserRole     = _user,
                    CreatedDate  = DateTime.Now,
                    ModifiedDate = DateTime.Now
                };

                _appDBContext.Add(userData);
                _appDBContext.SaveChanges();

                responseData = ResponseData(userData);
                return(responseData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #18
0
        public async Task Should_post_a_valid_Registration_message()
        {
            // Arrange
            var http      = new FakeHttpMessageHandler("http://baseaddress/");
            var directory = new Directory {
                NewRegistration = new Uri("http://baseaddress/registration")
            };
            var registration = new RegistrationResponse();

            var client =
                http.RequestTo("directory").Returns(directory).WithNonce("nonce").
                RequestTo("registration").Returns(registration).WithNonce("nonce").
                GetHttpClient();

            var sut = new AcmeClient(client, new RSACryptoServiceProvider());

            // Act
            var registrationResponse = await sut.RegisterAsync("agreementUri", new [] { "mailto:[email protected]" });

            // Assert
            registrationResponse.Should().NotBeNull();
            http.ReceivedRequestsTo("directory").Single().HasMethod(HttpMethod.Get);
            http.ReceivedRequestsTo("registration").Single().HasMethod(HttpMethod.Post).HasJwsPayload <NewRegistrationRequest>(r =>
            {
                r.Agreement.Should().Be("agreementUri");
                r.Contact.Should().Contain("mailto:[email protected]");
            });
        }
Example #19
0
        public IActionResult RegisterUser(UserRegistration user)
        {
            try
            {
                string           password = user.Password;
                UserRegistration data     = _BusinessLayer.register(user);
                if (!data.Equals(null))
                {
                    RegistrationResponse Data = new RegistrationResponse
                    {
                        FirstName = user.FirstName,
                        LastName  = user.LastName,
                        Email     = user.Email,
                        UserType  = user.UserType
                    };

                    string MSMQ = "\n First Name : " + Convert.ToString(user.FirstName) + "\n Last Name : " + Convert.ToString(user.LastName) +
                                  "\n User Role : " + Convert.ToString(user.UserType) +
                                  "\n Email : " + Convert.ToString(user.Email);
                    sender.Message(MSMQ);
                    return(Ok(new { success = true, Message = "Registration Successfull", Data = data }));
                }
                else
                {
                    return(this.Ok(new { success = false, Message = "Registration Failed" }));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(new { success = false, Message = e.Message }));
            }
        }
Example #20
0
        public async Task Should_POST_to_get_registration_details_if_the_registration_already_exists()
        {
            // Arrange
            var http      = new FakeHttpMessageHandler("http://baseaddress/");
            var directory = new Directory {
                NewRegistration = new Uri("http://baseaddress/registration")
            };
            var registration = new RegistrationResponse();

            var client =
                http.RequestTo("directory").Returns(directory).WithNonce("nonce").
                RequestTo("registration").Returns(new Problem(), "application/problem+json").HasStatusCode(HttpStatusCode.Conflict).WithHeader("Location", "http://baseaddress/existingreguri").WithNonce("nonce").
                RequestTo("existingreguri").Returns(registration).WithNonce("nonce").
                GetHttpClient();

            var sut = new AcmeClient(client, new RSACryptoServiceProvider());

            // Act
            var registrationResponse = await sut.RegisterAsync("agreementUri", new[] { "mailto:[email protected]" });

            // Assert
            registrationResponse.Should().NotBeNull();
            http.ReceivedRequestsTo("directory").Single().HasMethod(HttpMethod.Get);
            http.ReceivedRequestsTo("registration").Single().HasMethod(HttpMethod.Post).HasJwsPayload <NewRegistrationRequest>(r =>
            {
                r.Agreement.Should().Be("agreementUri");
                r.Contact.Should().Contain("mailto:[email protected]");
            });
            http.ReceivedRequestsTo("existingreguri").Single().HasMethod(HttpMethod.Post).HasJwsPayload <UpdateRegistrationRequest>(r =>
            {
                r.Agreement.Should().BeNull();
                r.Contact.Should().BeNull();
            });
        }
Example #21
0
        public RegistrationResponse Register(string email, string password)
        {
            var response = new RegistrationResponse {
                IsValid = true
            };

            var isEmailValid = validation.IsEmailValid(email);

            if (!isEmailValid)
            {
                response.IsValid = false;
                response.Errors  = new List <string> {
                    "Email is invalid"
                };
                return(response);
            }

            var isPasswordValid = validation.IsPassWordValid(password);

            if (!isPasswordValid.IsValid)
            {
                response.IsValid = false;
                response.Errors  = isPasswordValid.Reasons.ToList();
                return(response);
            }

            response.UserName = email;

            repository.Add(email, password);

            return(response);
        }
Example #22
0
        public RegistrationForm(RegistrationManager manager, RegistrationResponse registrationResponse)
        {
            InitializeComponent();

            registrationUrlLabel.Text     = registrationResponse.InviteUrl;
            registrationTokenTextBox.Text = registrationResponse.RegistrationToken;

            int   pollingCounter = 0;
            Timer pollingTimer   = null;

            pollingTimer = new Timer(state =>
            {
                pollingCounter++;
                var pollResult = manager.Poll(registrationResponse.PollingUrl).Result;

                if (pollResult.Success)
                {
                    pollingTimer.Dispose();

                    PollResponse = pollResult;
                    ShowSuccessResult();
                }
                else
                {
                    if (pollingCounter > 120) // 10 minutes
                    {
                        pollingTimer.Dispose();
                        ShowFailureResult();
                    }
                }
            }, null, 0, 5000);
        }
Example #23
0
    private void RegisterGameSparksResponse(RegistrationResponse response)
    {
        if (!response.HasErrors)
        {
            Debug.Log("Player Authenticated... \n User Name: " + response.DisplayName);
            GameSparksPlayerData.playerID   = response.UserId;
            GameSparksPlayerData.playerName = response.DisplayName;

            loginPanel.gameObject.SetActive(false);
            GameSparksDeviceLogin.alreadyLoggedIn = true;
            platoonPanel.SetActive(true);
            ServiceLocator.SaveSystem.GetPlayerDataFromServer();
            this.GetComponent <GameSparksMessageManager>().ProcessGenericMessages();
            ServiceLocator.AnalyticsDispatcher.DispatchAnalytics("playerRegistered");

            if (ABTest_SkipTutorial.flag && ServiceLocator.tutorialManager.skipButton != null)
            {
                ServiceLocator.tutorialManager.skipButton.GetComponent <Button> ().interactable = true;
            }
        }
        else
        {
            loginPanel.loginFailed();
            loginPanel.ErrorString = "Check your internet connection";
            IDictionary <string, object> errorDictionary = GSJson.From(response.Errors.JSON.ToString()) as IDictionary <string, object>;
            loginPanel.ErrorString = socialErrorManager.GetErrorMessage(errorDictionary ["error"].ToString());
            Debug.Log("Error Authenticating Player... \n " + response.Errors.JSON.ToString());
        }
    }
Example #24
0
        public async Task <RegistrationResponse> Registration(string username, string name, string email, string password, string repeatPassword)
        {
            var signup = Configuration["url"];
            RegistrationResponse response = await _httlClient.PostJsonAsync <RegistrationResponse>(signup + "api/User/Register", new RegistrationRequest(username, name, email, password, repeatPassword));

            return(response);
        }
Example #25
0
        void OnRegistrationSucessHandler(RegistrationResponse res, Context context)
        {
            System.Console.WriteLine("Successfully got callback in LoginActivity :" + res.Message);

            // Enable  below commented code for adding member to contact group

            /*  contactService = new ApplozicContactService(this);
             * contactService.AddMemberToContactGroup(this, contactGroupId, (String)(Channel.GroupType.ContactGroup.Value), userName.Text, addMemberListner);
             * var applozicPref = Com.Applozic.Mobicomkit.Api.Account.User.MobiComUserPreference.GetInstance(context);
             * applozicPref.ContactsGroupId = contactGroupId;  */

            ApplozicClient.GetInstance(context).SetHandleDial(true).IPCallEnabled = true;
            Dictionary <ApplozicSetting.RequestCode, string> activityCallbacks = new Dictionary <ApplozicSetting.RequestCode, string>();

            activityCallbacks.Add(ApplozicSetting.RequestCode.AudioCall, $"{"Com.Applozic.Audiovideo.Activity".ToLower()}.{nameof(AudioCallActivityV2)}");

            var videoActivity = $"{"Com.Applozic.Audiovideo.Activity".ToLower()}.{nameof(VideoActivity)}";

            activityCallbacks.Add(ApplozicSetting.RequestCode.VideoCall, videoActivity);
            ApplozicSetting.GetInstance(context).SetActivityCallbacks(activityCallbacks);
            Intent myIntent = new Intent(this, typeof(MainActivity));

            this.StartActivity(myIntent);
            this.Finish();
        }
        /// <summary>
        /// It Generate the token.
        /// </summary>
        /// <param name="adminDetails">Response Model</param>
        /// <param name="tokenType">Token Type</param>
        /// <returns>It return Token</returns>
        private string GenerateToken(RegistrationResponse adminDetails, string tokenType)
        {
            try
            {
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

                var claims = new[]
                {
                    new Claim("AdminID", adminDetails.ID.ToString()),
                    new Claim("Email", adminDetails.Email.ToString()),
                    new Claim("TokenType", tokenType),
                    new Claim("UserRole", adminDetails.UserRole.ToString())
                };

                var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Issuer"],
                                                 claims, expires: DateTime.Now.AddDays(1), signingCredentials: credentials);

                return(new JwtSecurityTokenHandler().WriteToken(token));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        public void Registering_invalid_customer_rop_should_have_correct_error()
        {
            // Arrange
            var customer = new Customer(CustomerName.TryCreate("test").Value);

            var customerRepository = Substitute.For <ICustomerRepository>();

            customerRepository
            .Save(Arg.Any <Customer>())
            .Returns(Result.Ok(customer));

            var mailService = Substitute.For <IMailService>();

            mailService
            .SendGreeting(Arg.Any <Customer>())
            .Returns(Result.Ok(customer));

            var sut = new RegistrationService(customerRepository, mailService);

            // Act
            var result = sut.RegisterNewCustomer_Error_Handling2("");

            // Assert
            result.Should()
            .BeEquivalentTo(RegistrationResponse.Fail("invalid name"));
        }
        public void Registering_valid_customer_happy_path_works()
        {
            // Arrange
            var customer = new Customer(CustomerName.TryCreate("test").Value);

            var customerRepository = Substitute.For <ICustomerRepository>();

            customerRepository
            .Save(Arg.Any <Customer>())
            .Returns(Result.Ok(customer));

            var mailService = Substitute.For <IMailService>();

            mailService
            .SendGreeting(Arg.Any <Customer>())
            .Returns(Result.Ok(customer));

            var sut = new RegistrationService(customerRepository, mailService);

            // Act
            var result = sut.RegisterNewCustomer_NoError_Handling("test");

            // Assert
            result.Should()
            .BeEquivalentTo(RegistrationResponse.Success(customer));
        }
Example #29
0
 internal RegistrationResponse Create(Client client)
 {
     if (client.Status == Convert.ToByte(ClientStatus.Verified))
     {
         string password          = new PasswordFactory().Generate(128);
         RegistrationResponse def = new RegistrationResponse()
         {
             //TODO: Create username, password and salt
             Username = client.ID.ToString(),
             Password = password,
             Status   = ClientStatus.Verified
         };
         client.Username = client.ID.ToString();
         client.Password = password;
         new ClientRepository().Update(client);
         return(def);
     }
     else
     {
         return(new RegistrationResponse()
         {
             Status = this.GetStatus(client.Status)
         });
     }
 }
        public async Task <IActionResult> Register([FromBody] RegistrationRequest request)
        {
            //TODO replace organisation name in the request with organisation UUID
            // this could reduce the change of brute force success on unrightfully registering users on an organisation
            Organisation organisation = await _unitOfWork.OrganisationRepository.GetByNameAsync(request.OrganisationName);

            User newUser = _unitOfWork.UserRepository.CreateUser(request, organisation, null);

            List <ErrorResponse> errorResponses = await _authService.ValidateRegistrationAsync(request, organisation, newUser);

            if (errorResponses.Any())
            {
                return(BadRequest(errorResponses));
            }
            var transaction = _unitOfWork.UserRepository.BeginTransaction();

            RegistrationResponse registrationResponse = await _authService.RegisterUserAsync(request, organisation, newUser);

            var locationURI = _URIService.GetUserURI(registrationResponse.ID);

            Dictionary <string, string> tokens = await _tokenService.GetTokensAsync(newUser);

            await transaction.CommitAsync();

            tokens.TryGetValue("SecurityToken", out string securityToken);
            tokens.TryGetValue("RefreshToken", out string refreshToken);

            registrationResponse.Token        = securityToken;
            registrationResponse.RefreshToken = refreshToken;

            return(Created(locationURI, new Response <RegistrationResponse>(registrationResponse)));
        }
Example #31
0
 public object Post(RegistrationRequest request)
 {
     //sprawdzenie czy user jest w bazie danych
     //wstawienei do bazy danych
     //odpowiedz do frontu
     User user1 = new User();
     user1.Firstname = request.Firstname.ToString();
     user1.Lastname = request.Lastname.ToString();
     user1.Login = request.Login.ToString();
     user1.Password = request.Password.ToString();
     RegistrationResponse Response = new RegistrationResponse();
     int result = Response.Session(request);
     base.Response.StatusCode = result;
     return Response;
 }
        public IHttpActionResult Register(RegistrationRequest request)
        {
            var response = new RegistrationResponse();

            try
            {
                var member = MembershipAdapter.GetMember(request.Email);

                if (member.Exists() && member.ConfirmedRegistration())
                {
                    request.AddError("Email", "Email already exists");
                }

                if (request.IsValidModel())
                {
                    if (!request.PasswordsMatch())
                    {
                        request.AddError("Password", "Passwords do not match");
                    }
                }

                if (!request.HasErrors())
                {
                    if (member.IsNewRegistration())
                    {
                        member.Email = request.Email;
                        member.RegistrationDate = DateTime.Now.ToUniversalTime();
                        member.IsActive = true;
                        member.IsAdmin = false;

                        member.Security = new MemberPassword();
                        member.Security.InitializePassword(request.Password);

                        member.Profile = new MemberProfile();
                        member.Profile.Alias = request.Alias;
                        member.Profile.TimeZoneId = ConfigHelper.DefaultTimeZoneId;

                        var registrationToken = new MemberToken();

                        registrationToken.Token = Guid.NewGuid();
                        registrationToken.TokenType = TokenTypes.Registration;
                        registrationToken.RequestDate = member.RegistrationDate;

                        member.Tokens.Add(registrationToken);

                        member = MembershipAdapter.AddMember(member);
                    }
                    else if (member.IsPendingRegistrationConfirmation())
                    {
                        member.Security.InitializePassword(request.Password);
                        member.Profile.Alias = request.Alias;

                        var registrationToken = MembershipAdapter.GetMemberTokens(member.Id, TokenTypes.Registration, true);

                        member.Tokens.Add(registrationToken.ElementAt(0));

                        member = MembershipAdapter.ReRegisterMember(member);
                    }

                    var email = new RegistrationEmail
                    {
                        DomainName = ConfigHelper.DomainName,
                        DomainBaseUrl = ConfigHelper.DomainBaseUrl,
                        Alias = request.Alias,
                        ConfirmationToken = member.Tokens.ElementAt(0).Token
                    };

                    var emailBuilder = new EmailBuilder(EmailReference.HTML.Templates.Main, EmailReference.HTML.Contents.Registration);
                    var emailBody = emailBuilder.BuildBody<RegistrationEmail>(email);
                    var emailResult = EmailHelper.SendEmail(ConfigHelper.NoReplayEmailAddress,
                                                            ConfigHelper.DomainName,
                                                            request.Email,
                                                            request.Alias,
                                                            email.Subject,
                                                            emailBody,
                                                            true);

                    if (emailResult)
                    {
                        response.IsSuccessful = true;
                        response.StatusMessage = "Registration succeeded";
                    }
                }
                else
                {
                    response.Errors.AddRange(request.GetErrors());
                    response.IsSuccessful = false;
                    response.StatusMessage = "Registration was unsuccessful";
                }
            }
            catch (Exception ex)
            {
                request.Password = string.Empty;
                request.PasswordConfirm = string.Empty;

                this.Log<RegistrationRequest>(LogCategories.Error, request, ex.Message);

                response.IsSuccessful = false;
                response.StatusMessage = this.StatusMessageForExpection;
                response.Errors.Add(ex.Message);
            }

            return Ok(response);
        }