예제 #1
0
        public object Put(UpdateBulkUsersProfileFromRemoteTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/users/profile PUT Ids='{0}'", string.Join(",", request.Identifiers)));

                foreach (var identifier in request.Identifiers)
                {
                    try
                    {
                        var usr = UserTep.FromIdentifier(context, identifier);
                        usr.LoadProfileFromRemote();
                    }catch (Exception e) {
                        context.LogError(this, e.Message + " - " + e.StackTrace);
                    }
                }

                try{
                    var portalname = string.Format("{0} Portal", context.GetConfigValue("SiteNameShort"));
                    var subject    = context.GetConfigValue("EmailBulkActionSubject");
                    subject = subject.Replace("$(SITENAME)", portalname);
                    var body = context.GetConfigValue("EmailBulkActionBody");
                    body = body.Replace("$(ADMIN)", context.Username);
                    body = body.Replace("$(ACTION)", "User remote profile load");
                    body = body.Replace("$(IDENTIFIERS)", string.Join(",", request.Identifiers));
                    context.SendMail(context.GetConfigValue("SmtpUsername"), context.GetConfigValue("SmtpUsername"), subject, body);
                } catch (Exception e) {
                    context.LogError(this, e.Message + " - " + e.StackTrace);
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message + " - " + e.StackTrace);
                context.Close();
                throw e;
            }

            return(true);
        }
예제 #2
0
        public object Put(UpdateBulkUsersLevelTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/users/level PUT Ids='{0}',level='{1}'", string.Join(",", request.Identifiers), request.Level));

                string ids = "";
                foreach (var id in request.Identifiers)
                {
                    ids += string.Format("'{0}',", id);
                }
                ids = ids.TrimEnd(',');
                string sql = string.Format("UPDATE usr SET level='{0}' WHERE username IN ({1});", request.Level, ids);
                context.Execute(sql);

                try{
                    var portalname = string.Format("{0} Portal", context.GetConfigValue("SiteNameShort"));
                    var subject    = context.GetConfigValue("EmailBulkActionSubject");
                    subject = subject.Replace("$(SITENAME)", portalname);
                    var body = context.GetConfigValue("EmailBulkActionBody");
                    body = body.Replace("$(ADMIN)", context.Username);
                    body = body.Replace("$(ACTION)", "User level update");
                    body = body.Replace("$(IDENTIFIERS)", string.Join(",", request.Identifiers));
                    context.SendMail(context.GetConfigValue("SmtpUsername"), context.GetConfigValue("SmtpUsername"), subject, body);
                } catch (Exception e) {
                    context.LogError(this, e.Message + " - " + e.StackTrace);
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message + " - " + e.StackTrace);
                context.Close();
                throw e;
            }

            return(true);
        }
        public override User GetUserProfile(IfyWebContext context, HttpRequest request = null, bool strict = false)
        {
            NewUserCreated = false;

            UserTep            usr      = null;
            AuthenticationType authType = IfyWebContext.GetAuthenticationType(typeof(TepLdapAuthenticationType));

            var tokenrefresh = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-refresh"));
            var tokenaccess  = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));

            context.LogDebug(this, string.Format("GetUserProfile -- tokenrefresh = {0} ; tokenaccess = {1}", tokenrefresh.Value, tokenaccess.Value));

            if (!string.IsNullOrEmpty(tokenrefresh.Value) && DateTime.UtcNow > tokenaccess.Expire)
            {
                // refresh the token
                try {
                    var tokenresponse = client.RefreshToken(tokenrefresh.Value);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-access"), tokenresponse.access_token, tokenaccess.Username, tokenresponse.expires_in);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-refresh"), tokenresponse.refresh_token, tokenrefresh.Username);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-id"), tokenresponse.id_token, tokenrefresh.Username, tokenresponse.expires_in);
                    tokenaccess = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));
                    context.LogDebug(this, string.Format("GetUserProfile - refresh -- tokenrefresh = {0} ; tokenaccess = {1}", tokenrefresh.Value, tokenaccess.Value));
                } catch (Exception) {
                    return(null);
                }
            }

            if (!string.IsNullOrEmpty(tokenaccess.Value))
            {
                OauthUserInfoResponse usrInfo = client.GetUserInfo(tokenaccess.Value);

                context.LogDebug(this, string.Format("GetUserProfile -- usrInfo"));

                if (usrInfo == null)
                {
                    return(null);
                }

                context.LogDebug(this, string.Format("GetUserProfile -- usrInfo = {0}", usrInfo.sub));

                //Check if association auth / username exists
                int  userId = User.GetUserId(context, usrInfo.sub, authType);
                bool userHasAuthAssociated = userId != 0;

                //user has ldap auth associated to his account
                if (userHasAuthAssociated)
                {
                    //User exists, we load it
                    usr = UserTep.FromId(context, userId);
                    //test if TerradueCloudUsername was set
                    if (string.IsNullOrEmpty(usr.TerradueCloudUsername))
                    {
                        usr.LoadCloudUsername();
                        if (string.IsNullOrEmpty(usr.TerradueCloudUsername))
                        {
                            usr.TerradueCloudUsername = usrInfo.sub;
                            usr.StoreCloudUsername();
                        }
                    }

                    //update user infos
                    if (!string.IsNullOrEmpty(usrInfo.given_name))
                    {
                        usr.FirstName = usrInfo.given_name;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.family_name))
                    {
                        usr.LastName = usrInfo.family_name;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.zoneinfo))
                    {
                        usr.TimeZone = usrInfo.zoneinfo;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.locale))
                    {
                        usr.Language = usrInfo.locale;
                    }

                    return(usr);
                }

                if (string.IsNullOrEmpty(usrInfo.email))
                {
                    throw new Exception("Null email returned by the Oauth mechanism, please contact support.");
                }

                //user does not have ldap auth associated to his account
                try {
                    //check if a user with the same email exists
                    usr = UserTep.FromEmail(context, usrInfo.email);

                    //user with the same email exists but not yet associated to ldap auth
                    usr.LinkToAuthenticationProvider(authType, usrInfo.sub);

                    return(usr);
                    //TODO: what about if user Cloud username is different ? force to new one ?
                } catch (Exception e) {
                    context.LogError(this, e.Message);
                }

                //user with this email does not exist, we should create it
                usr       = (UserTep)User.GetOrCreate(context, usrInfo.sub, authType);
                usr.Level = UserCreationDefaultLevel;

                //update user infos
                if (!string.IsNullOrEmpty(usrInfo.given_name))
                {
                    usr.FirstName = usrInfo.given_name;
                }
                if (!string.IsNullOrEmpty(usrInfo.family_name))
                {
                    usr.LastName = usrInfo.family_name;
                }
                if (!string.IsNullOrEmpty(usrInfo.email) && (TrustEmail || usrInfo.email_verifier))
                {
                    usr.Email = usrInfo.email;
                }
                if (!string.IsNullOrEmpty(usrInfo.zoneinfo))
                {
                    usr.TimeZone = usrInfo.zoneinfo;
                }
                if (!string.IsNullOrEmpty(usrInfo.locale))
                {
                    usr.Language = usrInfo.locale;
                }

                if (usr.Id == 0)
                {
                    usr.AccessLevel = EntityAccessLevel.Administrator;
                    NewUserCreated  = true;
                }

                usr.Store();

                usr.LinkToAuthenticationProvider(authType, usrInfo.sub);

                usr.TerradueCloudUsername = usrInfo.sub;
                usr.StoreCloudUsername();

                return(usr);
            }
            else
            {
            }

            context.LogDebug(this, string.Format("GetUserProfile -- return null"));

            return(null);
        }
예제 #4
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Sends a mail to a user.</summary>
        /// \ingroup Authorisation
        public bool SendMail(UserMailType type, bool forAuthenticatedUser)
        {
            IfyWebContext webContext = context as IfyWebContext; // TODO: replace

            string smtpHostname         = context.GetConfigValue("SmtpHostname");
            string smtpUsername         = context.GetConfigValue("SmtpUsername");
            string smtpPassword         = context.GetConfigValue("SmtpPassword");
            int    smtpPort             = context.GetConfigIntegerValue("SmtpPort");
            bool   smtpSsl              = context.GetConfigBooleanValue("SmtpSSL");
            string mailSenderAddress    = context.GetConfigValue("MailSenderAddress");
            string mailSender           = context.GetConfigValue("MailSender");
            string emailConfirmationUrl = context.GetConfigValue("EmailConfirmationUrl");

            if (String.IsNullOrEmpty(emailConfirmationUrl))
            {
                emailConfirmationUrl = String.Format(webContext.AccountRootUrl == null ? "{4}?_request={2}&key={3}" : "{0}{1}/{2}?key={3}",
                                                     webContext.BaseUrl,
                                                     webContext.AccountRootUrl,
                                                     type == UserMailType.Registration ? "activate" : "recover",
                                                     ActivationToken,
                                                     webContext.ScriptUrl
                                                     );
            }

            if (mailSender == null)
            {
                mailSender = mailSenderAddress;
            }

            if (smtpHostname == null || mailSenderAddress == null)
            {
                string errorMessage;
                if (type == UserMailType.Registration && !forAuthenticatedUser)
                {
                    errorMessage = "Your account could not be created due to a server misconfiguration (registration mail cannot be sent)";
                }
                else
                {
                    errorMessage = "Mail cannot be sent, missing values in SMTP account configuration (hostname or sender address)" + (context.UserLevel < UserLevel.Administrator ? ", this is a site administration issue" : String.Empty);
                }
                throw new Exception(errorMessage);
            }

            Load();

            string subject = null, body = null;
            bool   html = false;

            switch (type)
            {
            case UserMailType.Registration:
                subject = context.GetConfigValue("RegistrationMailSubject");
                body    = context.GetConfigValue("RegistrationMailBody");
                html    = context.GetConfigBooleanValue("RegistrationMailHtml");
                if (subject == null)
                {
                    subject = "Accout registration";
                }
                if (body == null)
                {
                    body = String.Format("Dear sir/madam,\n\nThank you for registering on {0}.\n\nYour username is: {1}\n\nBest regards,\nThe team of {0}\n\nP.S. Please do not reply to this mail, it has been generated automatically. If you think you received this mail by mistake, please ignore it.", context.GetConfigValue("SiteName"), Username);
                }
                break;

            case UserMailType.PasswordReset:
                subject = context.GetConfigValue("PasswordResetMailSubject");
                body    = context.GetConfigValue("PasswordResetMailBody");
                html    = context.GetConfigBooleanValue("PasswordResetMailHtml");
                if (subject == null)
                {
                    subject = "Password reset";
                }
                if (body == null)
                {
                    body = String.Format("Dear sir/madam,\n\nYour password for your user account on {0} has been changed.\n\nYour username is: {1}\n\nBest regards,\nThe team of {0}\n\nP.S. Please do not reply to this mail, it has been generated automatically. If you think you received this mail by mistake, please take into account that your password has changed.", context.GetConfigValue("SiteName"), Username);
                }
                break;

            case UserMailType.EmailChanged:
                subject = context.GetConfigValue("EmailChangedMailSubject");
                body    = context.GetConfigValue("EmailChangedMailBody");
                html    = context.GetConfigBooleanValue("EmailChangedMailHtml");
                if (subject == null)
                {
                    subject = "E-mail changed";
                }
                if (body == null)
                {
                    body = String.Format("Dear sir/madam,\n\nYou changed your e-mail address linked to your user account on {0}.\n\nPlease confirm the email by clicking on the following link:\n{1}\n\nBest regards,\nThe team of {0}\n\nP.S. Please do not reply to this mail, it has been generated automatically. If you think you received this mail by mistake, please take into account that your e-mail address has changed.", context.GetConfigValue("SiteName"), ActivationToken);
                }
                break;
            }

            var baseurl = webContext.GetConfigValue("BaseUrl");

            // activationToken also used here to avoid endless nested replacements
            subject = subject.Replace("$(SITENAME)", context.SiteName);
            body    = body.Replace(@"\n", Environment.NewLine);
            body    = body.Replace("$(", "$" + ActivationToken + "(");
            body    = body.Replace("$" + ActivationToken + "(USERCAPTION)", Caption);
            body    = body.Replace("$" + ActivationToken + "(USERNAME)", Username);
            body    = body.Replace("$" + ActivationToken + "(SITENAME)", context.SiteName);
            body    = body.Replace("$" + ActivationToken + "(SITEURL)", baseurl);
            body    = body.Replace("$" + ActivationToken + "(ACTIVATIONURL)", emailConfirmationUrl.Replace("$(BASEURL)", baseurl).Replace("$(TOKEN)", ActivationToken));
            if (body.Contains("$" + ActivationToken + "(SERVICES)"))
            {
                body = body.Replace("$" + ActivationToken + "(SERVICES)", GetUserAccessibleResourcesString(Service.GetInstance(context), html));
            }
            if (body.Contains("$" + ActivationToken + "(SERIES)"))
            {
                body = body.Replace("$" + ActivationToken + "(SERIES)", GetUserAccessibleResourcesString(Series.GetInstance(context), html));
            }

            MailMessage message = new MailMessage();

            message.From = new MailAddress(mailSenderAddress, mailSender);
            message.To.Add(new MailAddress(Email, Email));
            message.Subject = subject;

            if (html)
            {
                AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, new System.Net.Mime.ContentType("text/html"));
                message.AlternateViews.Add(alternate);
            }
            else
            {
                message.Body = body;
            }

            SmtpClient client = new SmtpClient(smtpHostname);

            // Add credentials if the SMTP server requires them.
            if (string.IsNullOrEmpty(smtpUsername))
            {
                smtpUsername                 = null;
                client.Credentials           = null;
                client.UseDefaultCredentials = false;
            }
            else if (smtpUsername != null)
            {
                client.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
            }
            if (smtpPassword == String.Empty)
            {
                smtpPassword = null;
            }

            if (smtpPort > 0)
            {
                client.Port = smtpPort;
            }

            client.EnableSsl      = smtpSsl;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            try {
                client.Send(message);
            } catch (Exception e) {
                if (e.Message.Contains("CDO.Message") || e.Message.Contains("535"))
                {
                    context.AddError("Mail could not be sent, this is a site administration issue (probably caused by an invalid SMTP hostname or wrong SMTP server credentials)");
                }
                else
                {
                    context.AddError("Mail could not be sent, this is a site administration issue: " + e.Message);
                }
                throw;
            }
            return(true);
        }