Beispiel #1
0
 public Client GenerateNewSecret(string id)
 {
     //TODO: invalidate existing refresh tokens?
     try
     {
         IClientAccount ca = _clientStorage.GetClient(id);
         if (ca != null)
         {
             ca.ClientSecret = Guid.NewGuid().ToString();
             _clientStorage.UpdateClient(id, ca);
             return(Client.CreateInstance(ca));
         }
         else
         {
             throw new HttpRequestException(JsonSerializer.SerializeJson(new ErrorMessage("Client does not exist", 500)), MimeType.APPLICATION_JSON)
                   {
                       Status = SKotstein.Net.Http.Context.HttpStatus.InternalServerError
                   };
         }
     }
     catch (HttpRequestException hre)
     {
         throw hre;
     }
     catch (Exception e)
     {
         throw new HttpRequestException(JsonSerializer.SerializeJson(new ErrorMessage(e.Message, 500)), MimeType.APPLICATION_JSON)
               {
                   Status = SKotstein.Net.Http.Context.HttpStatus.InternalServerError
               };
     }
 }
        public async Task <ClaimsIdentity> CreateUserIdentityAsync(IClientAccount clientAccount, string userName)
        {
            var personalData = await _personalDataRepository.GetAsync(clientAccount.Id);

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, clientAccount.Email),
                new Claim(ClaimTypes.NameIdentifier, clientAccount.Id),
                new Claim(OpenIdConnectConstants.Claims.Email, clientAccount.Email)
            };

            if (!string.IsNullOrEmpty(personalData.FirstName))
            {
                claims.Add(new Claim(OpenIdConnectConstants.Claims.GivenName, personalData.FirstName));
            }

            if (!string.IsNullOrEmpty(personalData.LastName))
            {
                claims.Add(new Claim(OpenIdConnectConstants.Claims.FamilyName, personalData.LastName));
            }

            if (!string.IsNullOrEmpty(personalData.Country))
            {
                claims.Add(new Claim(OpenIdConnectConstantsExt.Claims.Country, personalData.Country));
            }

            var documents = (await GetDocumentListAsync(clientAccount.Id)).ToList();

            if (documents.Any())
            {
                claims.Add(new Claim(OpenIdConnectConstantsExt.Claims.Documents, string.Join(",", documents)));
            }

            return(new ClaimsIdentity(new GenericIdentity(userName, "Token"), claims));
        }
Beispiel #3
0
        public async Task <IClientAccount> RegisterClientAsync(string email, string firstName, string lastName,
                                                               string phone, string password, string hint, string clientInfo, string ip, string changer, string language)
        {
            IClientAccount clientAccount = ClientAccount.Create(email, phone);

            clientAccount = await _clientAccountsRepository.RegisterAsync(clientAccount, password);

            var personalData = FullPersonalData.Create(clientAccount, firstName, lastName, hint);
            await _personalDataRepository.SaveAsync(personalData);

            await SetDefaultAssetGroups(clientAccount.Id);

            var fullname = personalData.GetFullName();

            var logEvent = RegistrationLogEvent.Create(clientAccount.Id, email, fullname, phone, clientInfo, ip);
            await _registrationLogs.RegisterEventAsync(logEvent);

            await _auditLogRepository.AddAuditRecordAsync(clientAccount.Id, null, personalData,
                                                          AuditRecordType.PersonalData, changer);

            await _srvEmailsFacade.SendWelcomeEmail(clientAccount.Email, clientAccount.Id);

            foreach (var registrationConsumer in _registrationConsumers)
            {
                registrationConsumer.ConsumeRegistration(clientAccount, ip, language);
            }

            return(clientAccount);
        }
Beispiel #4
0
        public static void AuthenticateUserViaOwin(this Controller ctx, IClientAccount user)
        {
            var authManager = ctx.HttpContext.GetOwinContext().Authentication;
            var identity = MakeIdentity(user);

            authManager.SignIn(new AuthenticationProperties {IsPersistent = false}, identity);
            ctx.SetCookie(EmailCookie, user.Email, DateTime.UtcNow.AddYears(1));

        }
Beispiel #5
0
        private static ClaimsIdentity MakeIdentity(IClientAccount user)
        {
            var claims = new List <Claim> {
                new Claim(ClaimTypes.Name, user.Id)
            };
            var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

            return(identity);
        }
Beispiel #6
0
        public static void AuthenticateUserViaOwin(this ApiController ctx, IClientAccount user)
        {
            var authManager = ctx.ControllerContext.Request.GetOwinContext().Authentication;
            var identity    = MakeIdentity(user);

            authManager.SignIn(new AuthenticationProperties {
                IsPersistent = false
            }, identity);
        }
Beispiel #7
0
 private void AssertClientAccount(IClientAccount ca)
 {
     Assert.AreEqual(true, ca.ClientAccountActive);
     Assert.AreEqual(3202, ca.ClientAccountID);
     Assert.AreEqual(true, ca.IsDefault);
     Assert.AreEqual(false, ca.Manager);
     Assert.AreEqual(true, ca.ClientAccountActive);
     AssertClient(ca);
     AssertAccount(ca);
 }
        public async Task<IClientAccount> RegisterAsync(IClientAccount clientAccount, string password)
        {
            var newEntity = ClientAccountEntity.CreateNew(clientAccount, password);
            var indexEntity = AzureIndex.Create(IndexEmail, newEntity.Email, newEntity);

            await _emailIndices.InsertAsync(indexEntity);
            await _tradersTableStorage.InsertAsync(newEntity);

            return newEntity;
        }
Beispiel #9
0
        public static void AuthenticateUserViaOwin(this Controller ctx, IClientAccount user)
        {
            var authManager = ctx.HttpContext.GetOwinContext().Authentication;
            var identity    = MakeIdentity(user);

            authManager.SignIn(new AuthenticationProperties {
                IsPersistent = false
            }, identity);
            ctx.SetCookie(EmailCookie, user.Email, DateTime.UtcNow.AddYears(1));
        }
Beispiel #10
0
        public async Task <IClientAccount> RegisterAsync(IClientAccount clientAccount, string password)
        {
            var newEntity   = ClientAccountEntity.CreateNew(clientAccount, password);
            var indexEntity = AzureIndex.Create(IndexEmail, newEntity.Email, newEntity);

            await _emailIndices.InsertAsync(indexEntity);

            await _clientsTablestorage.InsertAsync(newEntity);

            return(newEntity);
        }
 public static PersonalData Create(IClientAccount src, string firstname, string lastname)
 {
     return new PersonalData
     {
         Id = src.Id,
         Email = src.Email,
         ContactPhone = src.Phone,
         Regitered = src.Registered,
         FirstName = firstname,
         LastName = lastname
     };
 }
 public static PersonalData Create(IClientAccount src, string firstname, string lastname)
 {
     return(new PersonalData
     {
         Id = src.Id,
         Email = src.Email,
         ContactPhone = src.Phone,
         Regitered = src.Registered,
         FirstName = firstname,
         LastName = lastname
     });
 }
Beispiel #13
0
 public static FullPersonalData Create(IClientAccount src, string fullName, string pwdHint)
 {
     return(new FullPersonalData
     {
         Id = src.Id,
         Email = src.Email,
         ContactPhone = src.Phone,
         Regitered = src.Registered,
         FullName = fullName,
         Country = "CHE",
         PasswordHint = pwdHint
     });
 }
        public void DeleteClient(string clientId)
        {
            if (String.IsNullOrWhiteSpace(clientId))
            {
                throw new Exception("client ID is not set");
            }
            IClientAccount ca = GetClient(clientId);

            if (ca != null)
            {
                _clientAccounts.Remove(ca);
                RemoveFromDisk(clientId);
            }
        }
        public void ConsumeRegistration(IClientAccount account, string ip, string language)
        {
            lock (_lockObject)
            {
                _queue.Enqueue(new RegistrationEvent
                {
                    ClientAccount = account,
                    Ip            = ip,
                    Language      = language
                });
            }

            Task.Run(async() => await Execute());
        }
        public static ClientAccountEntity CreateNew(IClientAccount clientAccount, string password)
        {
            var result = new ClientAccountEntity
            {
                PartitionKey = GeneratePartitionKey(),
                RowKey = Guid.NewGuid().ToString(),
                Email = clientAccount.Email.ToLower(),
                Phone = clientAccount.Phone,
                Registered = clientAccount.Registered
            };

            result.SetPassword(password);

            return result;
        }
 public string CreateClient(IClientAccount data)
 {
     if (data == null)
     {
         throw new Exception("data is not set");
     }
     else
     {
         data.ClientId = "" + IdCounter;
         _clientAccounts.Add(data);
         SaveToDisk(data);
         IdCounter++;
         return(data.ClientId);
     }
 }
Beispiel #18
0
        public static ClientAccountEntity CreateNew(IClientAccount clientAccount, string password)
        {
            var result = new ClientAccountEntity
            {
                PartitionKey = GeneratePartitionKey(),
                RowKey       = Guid.NewGuid().ToString(),
                Email        = clientAccount.Email.ToLower(),
                Phone        = clientAccount.Phone,
                Registered   = clientAccount.Registered
            };

            result.SetPassword(password);

            return(result);
        }
Beispiel #19
0
        public async Task <IClientAccount> RegisterClientAsync(string email, string firstname, string lastname, string phone, string password)
        {
            IClientAccount clientAccount = ClientAccount.Create(email, phone);

            clientAccount = await _tradersRepository.RegisterAsync(clientAccount, password);

            await _srvSmsConfirmator.SendSmsAsync(clientAccount.Id);

            await _personalDataRepository.SaveAsync(PersonalData.Create(clientAccount, firstname, lastname));

            await RegisterAccountAsync(clientAccount, "EUR");
            await RegisterAccountAsync(clientAccount, "USD");
            await RegisterAccountAsync(clientAccount, "CHF");

            return(clientAccount);
        }
Beispiel #20
0
        public async Task <IClientAccount> RegisterAsync(IClientAccount clientAccount, string password)
        {
            var    newEntity   = ClientAccountEntity.CreateNew(clientAccount, password);
            string partnerId   = clientAccount.PartnerId;
            string indexRowKey = GetEmailPartnerIndexRowKey(newEntity);
            var    indexEntity = AzureIndex.Create(IndexEmail, indexRowKey, newEntity);
            ClientPartnerRelationEntity clientPartner =
                ClientPartnerRelationEntity.CreateNew(clientAccount.Email, newEntity.Id, newEntity.PartnerId);

            await _emailIndices.InsertAsync(indexEntity);

            await _clientsTablestorage.InsertAsync(newEntity);

            await _clientPartnerTablestorage.InsertAsync(clientPartner);

            return(newEntity);
        }
        public static ClientAccountEntity CreateNew(IClientAccount clientAccount, string password)
        {
            var result = new ClientAccountEntity
            {
                PartitionKey    = GeneratePartitionKey(),
                RowKey          = Guid.NewGuid().ToString(),
                NotificationsId = Guid.NewGuid().ToString("N"),
                Email           = clientAccount.Email.ToLower(),
                Phone           = clientAccount.Phone,
                Registered      = clientAccount.Registered,
                PartnerId       = clientAccount.PartnerId
            };

            PasswordKeepingUtils.SetPassword((IPasswordKeeping)result, password);

            return(result);
        }
Beispiel #22
0
        public decimal GetApportionment(IClientAccount ca, IRoom room, DateTime period)
        {
            if (ca == null)
            {
                return(0);
            }
            if (room == null)
            {
                return(0);
            }
            RoomApportionment appor = Session.Query <RoomApportionment>().FirstOrDefault(x => x.Client.ClientID == ca.ClientID && x.Account.AccountID == ca.AccountID && x.Room == room && x.Period == period);

            if (appor == null)
            {
                return(0);
            }
            return(appor.ChargeDays);
        }
        /// <summary>
        /// Checks whether the <see cref="Client"/> having the passed ID exists and whether it has users (see <see cref="Client.HasUser"/>).
        /// If not, a <see cref="HttpRequestException"/> with <see cref="HttpStatus.NotFound"/> will be thrown.
        /// </summary>
        /// <param name="clientId">ID of the <see cref="Client"/></param>
        private void CheckClient(string clientId)
        {
            IClientAccount client = _clientStorage.GetClient(clientId);

            if (client == null)
            {
                throw new HttpRequestException(JsonSerializer.SerializeJson(new ErrorMessage("The client with the ID: " + clientId + " does not exist", 404)), MimeType.APPLICATION_JSON)
                      {
                          Status = SKotstein.Net.Http.Context.HttpStatus.NotFound
                      };
            }
            if (!client.HasUser)
            {
                throw new HttpRequestException(JsonSerializer.SerializeJson(new ErrorMessage("The client with the ID: " + clientId + " has no user", 404)), MimeType.APPLICATION_JSON)
                      {
                          Status = SKotstein.Net.Http.Context.HttpStatus.NotFound
                      };
            }
        }
        public static ClientAccountJson CreateInstance(IClientAccount ca)
        {
            ClientAccountJson client = new ClientAccountJson();

            client.ClientId = ca.ClientId;
            client.AccessTokenExpiryInSeconds = ca.AccessTokenExpiryInSeconds;
            client.ClientSecret = ca.ClientSecret;
            client.Description  = ca.Description;
            client.FriendlyName = ca.FriendlyName;
            client.HasUser      = ca.HasUser;
            client.IsBlocked    = ca.IsBlocked;
            client.IsClientIdRequiredForRefreshToken      = ca.IsClientIdRequiredForRefreshToken;
            client.IsClientSecretRequiredForPasswordGrant = ca.IsClientSecretRequiredForPasswordGrant;
            client.IsClientSecretRequiredForRefreshToken  = ca.IsClientSecretRequiredForRefreshToken;
            client.IsUserIdRequiredForRefreshToken        = ca.IsUserIdRequiredForRefreshToken;
            client.IsUserPasswordRequiredForRefreshToken  = ca.IsUserPasswordRequiredForRefreshToken;
            client.RefreshTokenExpiryInSeconds            = ca.RefreshTokenExpiryInSeconds;
            client.Scope = ca.Scope;
            return(client);
        }
Beispiel #25
0
        public IClientAccount GetDryBoxClientAccount(int clientOrgId)
        {
            var q = Session.Query <ClientAccount>().Where(x => x.ClientOrg.ClientOrgID == clientOrgId);

            var join = q.Join(
                Session.Query <DryBoxAssignment>(),
                o => o.ClientAccountID,
                i => i.ClientAccountID,
                (o, i) => i);

            IClientAccount result = null;

            var dba = join.FirstOrDefault();

            if (dba != null)
            {
                var ca = Require <ClientAccount>(dba.ClientAccountID);
                result = ca.CreateModel <IClientAccount>();
            }

            return(result);
        }
        public async Task <IClientAccount> RegisterClientAsync(string email, string fullname, string phone, string password,
                                                               string hint, string clientInfo, string ip, string changer, double?iosVersion = null)
        {
            IClientAccount clientAccount = ClientAccount.Create(email, phone);

            clientAccount = await _clientAccountsRepository.RegisterAsync(clientAccount, password);

            await _clientSettingsRepository.SetSettings(clientAccount.Id, new HashedPwdSettings { IsPwdHashed = true });

            var personalData = FullPersonalData.Create(clientAccount, fullname, hint);
            await _personalDataRepository.SaveAsync(personalData);

            await SetDefaultAssetGroups(clientAccount.Id, iosVersion);

            var logEvent = RegistrationLogEvent.Create(clientAccount.Id, email, fullname, phone, clientInfo, ip);
            await _registrationLogs.RegisterEventAsync(logEvent);

            await _auditLogRepository.AddAuditRecordAsync(clientAccount.Id, null, personalData,
                                                          AuditRecordType.PersonalData, changer);

            await _srvEmailsFacade.SendWelcomeEmail(clientAccount.Email, clientAccount.Id);

            await
            _backgroundWorkRequestProducer.ProduceRequest(WorkType.SetGeolocation,
                                                          new SetGeolocationContext(clientAccount.Id, ip));

            await
            _backgroundWorkRequestProducer.ProduceRequest(WorkType.SetReferralCode,
                                                          new SetReferralCodeContext(clientAccount.Id, ip));

            await
            _backgroundWorkRequestProducer.ProduceRequest(WorkType.SetAntiFraudRecord,
                                                          new SetAntiFraudContext(clientAccount.Id, ip, email, fullname, phone));

            return(clientAccount);
        }
        public void UpdateClient(string clientId, IClientAccount data)
        {
            if (String.IsNullOrWhiteSpace(clientId))
            {
                throw new Exception("client ID is not set");
            }
            if (data == null)
            {
                throw new Exception("data is not set");
            }
            IClientAccount ca = GetClient(clientId);

            if (ca == null)
            {
                throw new Exception("Client does not exist");
            }
            else
            {
                ca.AccessTokenExpiryInSeconds = data.AccessTokenExpiryInSeconds;
                ca.ClientSecret = data.ClientSecret;
                ca.IsBlocked    = data.IsBlocked;
                ca.RefreshTokenExpiryInSeconds = data.RefreshTokenExpiryInSeconds;
                ca.Scope   = data.Scope;
                ca.HasUser = data.HasUser;
                ca.IsClientIdRequiredForRefreshToken      = data.IsClientIdRequiredForRefreshToken;
                ca.IsClientSecretRequiredForPasswordGrant = data.IsClientSecretRequiredForPasswordGrant;
                ca.IsClientSecretRequiredForRefreshToken  = data.IsClientSecretRequiredForRefreshToken;
                ca.IsUserIdRequiredForRefreshToken        = data.IsUserIdRequiredForRefreshToken;
                ca.IsUserPasswordRequiredForRefreshToken  = data.IsUserPasswordRequiredForRefreshToken;
                ca.FriendlyName = data.FriendlyName;
                ca.Description  = data.Description;

                data.ClientId = clientId;
                SaveToDisk(data);
            }
        }
        public void Authorize(HttpContext context, IDictionary <string, string> query)
        {
            string clientId       = "";
            string clientSecret   = "";
            string requestedScope = "";

            //expected but already parsed input is: grant_type
            //expected input is: client_id, client_secret
            //optional input is: scope


            //load client ID
            if (query.ContainsKey("client_id"))
            {
                clientId = query["client_id"];
            }
            else
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_REQUEST;
                errorResponse.Error_description = "The client ID is missing. The request must include the query parameter 'client_id'";
                //TODO: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.BadRequest;
                return;
            }

            //load client secret
            if (query.ContainsKey("client_secret"))
            {
                clientSecret = query["client_secret"];
            }
            else
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_REQUEST;
                errorResponse.Error_description = "The client secret is missing. The request must include the query parameter 'client_secret'";
                //TODO: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.BadRequest;
                return;
            }

            //load scope
            if (query.ContainsKey("scope"))
            {
                requestedScope = query["scope"];
            }

            //step 1: check whether: 1) client exists, 2) client is not blocked, 3) credentials are correct
            IClientAccount client = _storage.GetClient(clientId);

            if (client == null || client.IsBlocked || client.ClientSecret.CompareTo(clientSecret) != 0)
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_CLIENT;
                errorResponse.Error_description = "The client ID or secret is invalid";
                //TPDP: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.Unauthorized;
                return;
            }

            //step 2: validate scope
            string finalScope = "";

            if (String.IsNullOrWhiteSpace(requestedScope))
            {
                finalScope = client.Scope;
            }
            else
            {
                //extract single scopes from requested scope
                string[] scopes;
                if (requestedScope.Contains(","))
                {
                    scopes = requestedScope.Split(',');
                }
                else if (requestedScope.Contains(";"))
                {
                    scopes = requestedScope.Split(';');
                }
                else if (requestedScope.Contains(" "))
                {
                    scopes = requestedScope.Split(' ');
                }
                else
                {
                    scopes = new string[] { requestedScope };
                }

                //check whether all requested scopes are permitted:
                IList <string> permittedScope = client.GetScopeAsList;
                foreach (string scope in scopes)
                {
                    if (!permittedScope.Contains(scope))
                    {
                        InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                        errorResponse.Error             = InvalidAuthorizationResponse.INVALID_SCOPE;
                        errorResponse.Error_description = "The scope '" + scope + "' is not permitted or unknown";
                        //TODO: add URL
                        context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                        context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                        context.Response.Status = HttpStatus.BadRequest;
                        return;
                    }
                    finalScope += scope + " ";
                }
                finalScope.Trim();
            }

            //step 3: create access token and (if applicable) refresh token
            AccessToken accessToken  = _reference.GenerateAccessToken(null, clientId, finalScope, client.AccessTokenExpiryInSeconds);
            string      refreshToken = _reference.GenerateRefreshToken(null, clientId, finalScope, client.RefreshTokenExpiryInSeconds);

            //step 4: return access token and (if applicable) refresh token
            accessToken.RefreshToken = refreshToken;
            context.Response.Payload.Write(JsonSerializer.SerializeJson(accessToken));
            context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
            context.Response.Headers.Set("Cache-Control", "no-store");
            context.Response.Headers.Set("Pragma", "no-cache");
            context.Response.Status = HttpStatus.OK;
        }
        public void Authorize(HttpContext context, IDictionary <string, string> query)
        {
            string username       = "";
            string password       = "";
            string clientId       = "";
            string clientSecret   = "";
            string requestedScope = "";

            //expected but already parsed input is: grant_type
            //expected input is: username, password
            //optional input is: scope

            //load username
            if (query.ContainsKey("username"))
            {
                username = query["username"];
            }
            else
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_REQUEST;
                errorResponse.Error_description = "The username is missing. The request must include the query parameter 'username'";
                //TODO: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.BadRequest;
                return;
            }

            //load password
            if (query.ContainsKey("password"))
            {
                password = query["password"];
            }
            else
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_REQUEST;
                errorResponse.Error_description = "The password is missing. The request must include the query parameter 'password'";
                //TODO: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.BadRequest;
                return;
            }

            //load client ID:
            if (query.ContainsKey("client_id"))
            {
                clientId = query["client_id"];
            }
            else
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_REQUEST;
                errorResponse.Error_description = "The client ID is missing. The request must include the query parameter 'client_id'";
                //TODO: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.BadRequest;
                return;
            }

            //load client secret
            if (query.ContainsKey("client_secret"))
            {
                clientSecret = query["client_secret"];
            }

            //load scope
            if (query.ContainsKey("scope"))
            {
                requestedScope = query["scope"];
            }

            //step 1: check whether: 1) client exists, 2) client is not blocked, 3) client has user
            IClientAccount client = _clientStorage.GetClient(clientId);

            if (client == null || client.IsBlocked || !client.HasUser)
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_CLIENT;
                errorResponse.Error_description = "The client ID is invalid";
                //TPDP: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.Unauthorized;
                return;
            }

            //step 2 (if applicable): 1) check whether client's secret is set (if enabled) and 2) if it is correct
            if (client.IsClientSecretRequiredForPasswordGrant)
            {
                if (String.IsNullOrWhiteSpace(clientSecret))
                {
                    InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                    errorResponse.Error             = InvalidAuthorizationResponse.INVALID_REQUEST;
                    errorResponse.Error_description = "The client secret is missing. The request must include the query parameter 'client_secret'";
                    //TODO: add URI
                    context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                    context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                    context.Response.Status = HttpStatus.BadRequest;
                    return;
                }
                if (client.ClientSecret.CompareTo(clientSecret) != 0)
                {
                    InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                    errorResponse.Error             = InvalidAuthorizationResponse.INVALID_CLIENT;
                    errorResponse.Error_description = "The client ID or secret is invalid";
                    //TODO: add URI
                    context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                    context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                    context.Response.Status = HttpStatus.Unauthorized;
                    return;
                }
            }

            //step 3: check whether 1) user exists, 2) user is not blocked, 3) password is correct and 4) the user belongs to the passed client
            IUserAccount user = _userStorage.GetUserByName(username);

            if (user == null || user.IsBlocked || user.Password.CompareTo(password) != 0 || user.ClientId.CompareTo(clientId) != 0)
            {
                InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                errorResponse.Error             = InvalidAuthorizationResponse.INVALID_CLIENT;
                errorResponse.Error_description = "The username or password invalid";
                //TODO: add URI
                context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                context.Response.Status = HttpStatus.Unauthorized;
                return;
            }

            //step 4: validate scope
            string finalScope = "";

            if (String.IsNullOrWhiteSpace(requestedScope))
            {
                finalScope = user.Scope;
            }
            else
            {
                //extract single scopes from requested scope
                string[] scopes;
                if (requestedScope.Contains(","))
                {
                    scopes = requestedScope.Split(',');
                }
                else if (requestedScope.Contains(";"))
                {
                    scopes = requestedScope.Split(';');
                }
                else if (requestedScope.Contains(" "))
                {
                    scopes = requestedScope.Split(' ');
                }
                else
                {
                    scopes = new string[] { requestedScope };
                }

                //check whether all requested scopes are permitted:
                IList <string> permittedScope = user.GetScopeAsList;
                foreach (string scope in scopes)
                {
                    if (!permittedScope.Contains(scope))
                    {
                        InvalidAuthorizationResponse errorResponse = new InvalidAuthorizationResponse();
                        errorResponse.Error             = InvalidAuthorizationResponse.INVALID_SCOPE;
                        errorResponse.Error_description = "The scope '" + scope + "' is not permitted or unknown";
                        //TODO: add URL
                        context.Response.Payload.Write(JsonSerializer.SerializeJson(errorResponse));
                        context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
                        context.Response.Status = HttpStatus.BadRequest;
                        return;
                    }
                    finalScope += scope + " ";
                }
                finalScope.Trim();
            }

            //step 6: create access token and (if applicable) refresh token
            AccessToken accessToken  = _reference.GenerateAccessToken(username, clientId, finalScope, client.AccessTokenExpiryInSeconds);
            string      refreshToken = _reference.GenerateRefreshToken(username, clientId, finalScope, client.RefreshTokenExpiryInSeconds);

            //step 7: return access token and (if applicable) refresh token
            accessToken.RefreshToken = refreshToken;
            context.Response.Payload.Write(JsonSerializer.SerializeJson(accessToken));
            context.Response.Headers.Set("Content-Type", MimeType.APPLICATION_JSON);
            context.Response.Headers.Set("Cache-Control", "no-store");
            context.Response.Headers.Set("Pragma", "no-cache");
            context.Response.Status = HttpStatus.OK;
        }
Beispiel #30
0
 public static void AuthenticateUserViaOwin(this ApiController ctx, IClientAccount user)
 {
     var authManager = ctx.ControllerContext.Request.GetOwinContext().Authentication;
     var identity = MakeIdentity(user);
     authManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
 }
Beispiel #31
0
 public static void SetIdentity(this IClientAccount account)
 {
     ApiDependencies.GetIdentity = o => account.Id;
 }
        /// <summary>
        /// Saves the passed <see cref="IClientAccount"/> to disk.
        /// </summary>
        /// <param name="data">data to be saved</param>
        private void SaveToDisk(IClientAccount data)
        {
            ClientAccountJson caj = ClientAccountJson.CreateInstance(data);

            File.WriteAllText(_homeDirectory + data.ClientId + ".json", JsonSerializer.SerializeJson(caj));
        }
Beispiel #33
0
 private static ClaimsIdentity MakeIdentity(IClientAccount user)
 {
     var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.Id) };
     var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
     return identity;
 }
Beispiel #34
0
        private async Task RegisterAccountAsync(IClientAccount client, string currencyId)
        {
            var lykkeAccount = await _srvLykkeWallet.GenerateAccountsAsync(currencyId);

            await _accountsRepository.RegisterAccount(Account.Create(client.Id, lykkeAccount.Id, 0, currencyId));
        }
Beispiel #35
0
        public Client UpdateClient(string id, Client client)
        {
            try
            {
                IClientAccount ca = _clientStorage.GetClient(id);
                if (ca != null)
                {
                    if (client.HasPropertySet[Client.NAME_PROPERTY])
                    {
                        ca.FriendlyName = client.FriendlyName;
                    }
                    if (client.HasPropertySet[Client.DESCRIPTION_PROPERTY])
                    {
                        ca.Description = client.Description;
                    }
                    if (client.HasPropertySet[Client.SCOPE_PROPOERTY])
                    {
                        ca.Scope = client.Scope;
                    }
                    if (client.HasPropertySet[Client.IS_BLOCKED_PROPERTY])
                    {
                        ca.IsBlocked = client.IsBlocked;
                    }
                    if (client.HasPropertySet[Client.ACCESS_TOKEN_EXPIRY_PROPERTY])
                    {
                        ca.AccessTokenExpiryInSeconds = client.AccessTokenExpiryInSeconds;
                    }
                    if (client.HasPropertySet[Client.REFRESH_TOKEN_EXPIRY_PROPERTY])
                    {
                        ca.RefreshTokenExpiryInSeconds = client.RefreshTokenExpiryInSeconds;
                    }
                    if (client.HasPropertySet[Client.HAS_USER_PROPERTY])
                    {
                        ca.HasUser = client.HasUser;
                    }
                    if (client.HasPropertySet[Client.IS_CLIENT_ID_REQUIRED_FOR_REFRESH_TOKEN])
                    {
                        ca.IsClientIdRequiredForRefreshToken = client.IsClientIdRequiredForRefreshToken;
                    }
                    if (client.HasPropertySet[Client.IS_CLIENT_SECRET_REQUIRED_FOR_REFRESH_TOKEN])
                    {
                        ca.IsClientSecretRequiredForRefreshToken = client.IsClientSecretRequiredForRefreshToken;
                    }
                    if (client.HasPropertySet[Client.IS_USER_ID_REQUIRED_FOR_REFRESH_TOKEN])
                    {
                        ca.IsUserIdRequiredForRefreshToken = client.IsUserIdRequiredForRefreshToken;
                    }
                    if (client.HasPropertySet[Client.IS_USER_PASSWORD_REQUIRED_FOR_REFRESH_TOKEN])
                    {
                        ca.IsUserPasswordRequiredForRefreshToken = client.IsUserPasswordRequiredForRefreshToken;
                    }
                    if (client.HasPropertySet[Client.IS_CLIENT_SECRET_REQUIRED_FOR_PASSWORD_GRANT])
                    {
                        ca.IsClientSecretRequiredForPasswordGrant = client.IsClientSecretRequiredForPasswordGrant;
                    }

                    _clientStorage.UpdateClient(id, ca);

                    Client c = Client.CreateInstance(ca);
                    c.ClientSecret = "*********"; //hide secret
                    return(c);
                }
                else
                {
                    throw new HttpRequestException(JsonSerializer.SerializeJson(new ErrorMessage("Client does not exist", 404)), MimeType.APPLICATION_JSON)
                          {
                              Status = SKotstein.Net.Http.Context.HttpStatus.NotFound
                          };
                }
            }
            catch (HttpRequestException hre)
            {
                throw hre;
            }
            catch (Exception e)
            {
                throw new HttpRequestException(JsonSerializer.SerializeJson(new ErrorMessage(e.Message, 500)), MimeType.APPLICATION_JSON)
                      {
                          Status = SKotstein.Net.Http.Context.HttpStatus.InternalServerError
                      };
            }
        }
 private async Task RegisterAccountAsync(IClientAccount client, string currencyId)
 {
     var lykkeAccount = await _srvLykkeWallet.GenerateAccountsAsync(currencyId);
     await _accountsRepository.RegisterAccount(Account.Create(client.Id, lykkeAccount.Id, 0, currencyId));
 }
 public decimal GetApportionment(IClientAccount ca, IRoom room, DateTime period)
 {
     throw new NotImplementedException();
 }