コード例 #1
0
ファイル: UserService.cs プロジェクト: GusLab/video-portal
        public async Task<DomainUser> AddAsync(DomainUser entity)
        {
            entity.MaximumStorageSpace = _defaultUserStorageSpace;
            entity.Created = DateTime.UtcNow;
            entity.Modified = DateTime.UtcNow;
            entity.Timezone = entity.Timezone ?? DefaultTimezone;

            // normalizing email
            if (!string.IsNullOrEmpty(entity.Email))
            {
                entity.Email = entity.Email.ToLowerInvariant();
            }

            // truncating name if the name is email
            if (!string.IsNullOrEmpty(entity.Name))
            {
                var index = entity.Name.IndexOf("@", StringComparison.Ordinal);
                if (index > 0)
                {
                    entity.Name = entity.Name.Substring(0, index);
                }
            }

            var user = _mapper.Map<DomainUser, UserEntity>(entity);
            user = await _userRepository.AddAsync(user);

            return _mapper.Map<UserEntity, DomainUser>(user);
        }
コード例 #2
0
        public async Task<string> SetUserAsync(DomainUser user, TokenData tokenData, bool isPersistent = false)
        {
            if (tokenData != null && tokenData.IdentityProvider != ProviderType.Email)
            {
                await _userRepository.UpdateMembershipAsync(user.Id, _mapper.Map<TokenData, UserMembershipEntity>(tokenData));
            }

            string identityProvider = tokenData == null ? null : tokenData.IdentityProvider.ToString();
            return _authenticator.Authenticate(_mapper.Map<DomainUser, UserEntity>(user), identityProvider, isPersistent);
        }
コード例 #3
0
        public async Task SendNewRecoveryMail(DomainUser user, string validationPath)
        {
            string guid = Guid.NewGuid().ToString();
            DateTime expires = DateTime.UtcNow.Add(_expirationTime);
            var recoveryLink = new RecoveryLink { ExpirationDate = expires, Id = guid };

            PasswordRecoveryEntity entity = _passwordRecoveryFactory.CreateDefault(user.Id, guid, user.Email, expires);
            PasswordRecoveryEntity recoveryEntity = await _passwordRecoverRepository.AddAsync(entity);

            string linkRoot = _settings.PortalUri + validationPath;
            string linkText = _recoveryLinkService.CreateRecoveryLinkText(recoveryLink, linkRoot);

            Email emailToSend = ComposeRecoveryMail(recoveryEntity, user.Name, linkText);
            await _mailerRepository.SendMail(emailToSend);
        }
コード例 #4
0
        public async Task SendWelcomeMessageAsync(DomainUser user, TokenData data)
        {
            string facebookMessage = _settings.FacebookRegistrationMessage;
            if (String.IsNullOrEmpty(facebookMessage))
            {
                return;
            }

            if (data == null || string.IsNullOrEmpty(data.Token))
            {
                throw new ArgumentNullException("data");
            }

            JObject message = JObject.Parse(facebookMessage);

            var fb = new FacebookClient(data.Token);
            var post = new
            {
                caption = (string)message["caption"],
                message = (string)message["message"],
                name = (string)message["name"],
                description = (string)message["description"],
                picture = (string)message["picture"],
                link = (string)message["link"]
            };

            try
            {
                await fb.PostTaskAsync("me/feed", post);
            }
            catch (FacebookOAuthException e)
            {
                //Permission error
                if (e.ErrorCode != 200)
                {
                    throw new BadRequestException(e);
                }
            }
            catch (WebExceptionWrapper e)
            {
                throw new BadGatewayException(e);
            }
        }
コード例 #5
0
        public async Task<HttpResponseMessage> Post(RegisterUserModel model)
        {
            // Add profile
            var user = new DomainUser
            {
                ApplicationName = AppName,
                Name = model.UserName,
                Email = model.Email,
                Roles = new List<string> { DomainRoles.User },
                UserAgent = _productIdExtractor.Get(UserAgent)
            };

            user = await _userService.AddAsync(user);

            // Set user password
            await _passwordService.ChangePasswordAsync(user.Id, model.Password);

            try
            {
                await _emailNotificationService.SendRegistrationEmailAsync(user);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to send registration e-mail to {0}: {1}", model.Email, e);
            }

            Profile profile = _mapper.Map<DomainUser, Profile>(user);
            profile.AvatarUrl = _avatarProvider.GetAvatar(user);

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, profile);
            response.SetLastModifiedDate(user.Modified);

            await _authenticationService.SetUserAsync(user, new TokenData { IdentityProvider = ProviderType.Email }, true);

            return response;
        }
コード例 #6
0
        public async Task<ActionResult> ActivateClient(string code)
        {
            DomainPendingClient model;

            try
            {
                model = await _pendingClientService.GetAndDeleteAsync(code);
            }
            catch (NotFoundException)
            {
                return (ActionResult)RedirectToAction("Index", "Home");
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to find client: {0}", e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Add profile
            var user = new DomainUser
            {
                ApplicationName = AppName,
                Name = model.ContactPerson,
                Country = model.Country,
                UserAgent = _productIdExtractor.Get(Request.UserAgent),
                Email = model.Email,
                Roles = new List<string> { DomainRoles.Client }
            };

            try
            {
                user = await _userService.AddAsync(user);
            }
            catch (ConflictException)
            {
                return new HttpStatusCodeResult(HttpStatusCode.Conflict);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to create user profile for {0}: {1}", model.Email, e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Set user password
            try
            {
                await _passwordService.SetPasswordAsync(user.Id, model.Password, model.PasswordSalt);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to set user {0} password: {1}", user.Id, e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Add company
            var company = new DomainCompany
            {
                Email = model.Email,
                Name = model.CompanyName,
                Address = model.Address,
                ZipCode = model.ZipCode,
                Phone = model.PhoneNumber,
                Country = model.Country,
                Ein = model.Ein,
                Users = new List<string> { user.Id }
            };

            try
            {
                await _companyService.AddAsync(company);
            }
            catch (Exception e)
            {
                Trace.TraceError("Failed to create company for user {0}: {1}", user.Id, e);
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            // Authenticate
            await _authenticationService.SetUserAsync(user, null, true);

            return RedirectToRoute(RouteNames.ClientSubscriptions);
        }
コード例 #7
0
 public void UpdateIdentityClaims(DomainUser user)
 {
     _authenticator.UpdateIdentityClaims(user.Id, user.Email, user.Name, null);
 }
コード例 #8
0
        public async Task<HttpResponseMessage> Post(SessionIpModel model)
        {
            ITokenDataExtractor tokenDataExtractor = _tokenDataExtractorFactory.CreateTokenDataExtractor(model.Type);

            TokenData tokenData;

            try
            {
                tokenData = tokenDataExtractor.Get(model);
            }
            catch (BadRequestException)
            {
                ModelState.AddModelError("Token", ResponseMessages.AccountsInvalidToken);
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            // Return result
            DomainUser user = null;

            try
            {
                user = await _userService.FindByIdentityAsync(tokenData.IdentityProvider, tokenData.UserIdentifier);
            }
            catch (NotFoundException)
            {
            }

            // Try to find user by email
            if (user == null && !string.IsNullOrEmpty(tokenData.Email))
            {
                try
                {
                    user = await _userService.FindByEmailAsync(tokenData.Email);
                }
                catch (NotFoundException)
                {
                }

                // Add ip memebership to user
                if (user != null)
                {
                    await _userService.AddMembersipAsync(user.Id, tokenData);
                }
            }

            var httpStatusCode = HttpStatusCode.OK;

            // Check whether registration is required
            if (user == null)
            {
                var profileData = new DomainUser
                {
                    ApplicationName = AppName,
                    Name = tokenData.Name,
                    Email = tokenData.Email,
                    UserAgent = _productIdExtractor.Get(UserAgent),
                    Roles = new List<string> { DomainRoles.User },
                    Memberships = new List<UserMembership>
                    {
                        new UserMembership
                        {
                            IdentityProvider = tokenData.IdentityProvider,
                            UserIdentifier = tokenData.UserIdentifier,
                        }
                    }
                };

                user = await _userService.AddAsync(profileData);

                // Send registration e-mail
                try
                {
                    await _emailNotificationService.SendRegistrationEmailAsync(user);
                }
                catch (Exception e)
                {
                    Trace.TraceError("Failed to send registration email to address {0} for user {1}: {2}", user.Email, user.Id, e);
                }

                // Send notification into social network
                ISocialNetworkNotifier notifier = _notificationFactory.GetNotifier(tokenData.IdentityProvider);
                if (notifier != null)
                {
                    try
                    {
                        await notifier.SendWelcomeMessageAsync(user, tokenData);
                    }
                    catch (BadGatewayException)
                    {
                    }
                    catch (Exception e)
                    {
                        Trace.TraceError("Failed to send welcome message to user {0}: {1}", user.Id, e);
                    }
                }

                httpStatusCode = HttpStatusCode.Created;
            }

            var token = await _authenticationService.SetUserAsync(user, tokenData, true);
            return Request.CreateResponse(httpStatusCode, new AuthenticationTokenModel { Token = token });
        }
コード例 #9
0
        public Task SendRegistrationEmailAsync(DomainUser user)
        {
            if (string.IsNullOrEmpty(user.Email) || !_settings.EmailNotifications)
            {
                return Task.FromResult(0);
            }

            switch (user.UserAgent)
            {
                case ProductType.CicPc:
                case ProductType.CicMac:
                case ProductType.CicIPad:
                case ProductType.TaggerAndroid:
                case ProductType.TaggerIPhone:
                case ProductType.YoutubePlayer:
                case ProductType.DailyMotion:
                case ProductType.Other:
                    break;

                default:
                    return Task.FromResult(0);
            }

            var email = new SendEmailDomain
            {
                Address = _settings.EmailAddressInfo,
                DisplayName = Emails.SenderDisplayName,
                Emails = new List<string> { user.Email },
                Subject = Emails.SubjectRegistration,
                UserId = user.Id,
                Body = string.Format(PortalResources.UserRegistration, user.Name)
            };

            // Send email on user registration
            return _emailSenderService.SendEmailAsync(email);
        }
コード例 #10
0
        public Task SendVideoCommentNotificationAsync(DomainUser user, DomainProject project, DomainComment domainComment)
        {
            var email = new SendEmailDomain
            {
                Address = _settings.EmailAddressInfo,
                DisplayName = Emails.SenderDisplayName,
                Emails = new List<string> { user.Email },
                Subject = Emails.SubjectVideoComment,
                UserId = user.Id,
                Body = string.Format(PortalResources.VideoCommentNotification,
                    user.Name,
                    _userUriProvider.GetUri(domainComment.UserId),
                    domainComment.UserName,
                    _projectUriProvider.GetUri(project.Id),
                    project.Name,
                    domainComment.Body,
                    _settings.PortalUri)
            };

            // Send email on user registration
            return _emailSenderService.SendEmailAsync(email);
        }
コード例 #11
0
        public async Task SendAbuseNotificationAsync(Watch project, DomainUser reporter)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (reporter == null)
            {
                throw new ArgumentNullException("reporter");
            }

            if (!_settings.EmailNotifications)
            {
                return;
            }

            string projectUri = _projectUriProvider.GetUri(project.Id);
            var email = new SendEmailDomain
            {
                Address = _settings.EmailAddressAlerts,
                DisplayName = Emails.SenderDisplayName,
                Emails = new List<string> { _settings.EmailAddressAbuse },
                Subject = string.Format(Emails.SubjectAbuseReport, projectUri),
                Body = string.Format(
                    PortalResources.AbuseReported,
                    reporter.Name,
                    _userUriProvider.GetUri(reporter.Id),
                    project.Name,
                    projectUri)
            };

            // Send email
            await _emailSenderService.SendEmailAsync(email);
        }
コード例 #12
0
 public string GetAvatar(DomainUser user, string scheme = "http")
 {
     return GetAvatar(user != null ? user.Email : null, scheme);
 }