Example #1
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (IsBasicAuthorized(actionContext))
            {
                ((apiController)actionContext.ControllerContext.Controller).Init();
                return;
            }

            if (IsServerAuthorized(actionContext))
            {
                return;
            }

            if (IsAnonymous(actionContext))
            {
                return;
            }

            base.OnAuthorization(actionContext);

            ClaimsPrincipal principal = actionContext.Request.GetRequestContext().Principal as ClaimsPrincipal;

            var ci = principal.Identity as ClaimsIdentity;

            if (!ci.IsAuthenticated)
            {
                AuthorizationTokenExpiredException authorizationTokenExpiredException = new AuthorizationTokenExpiredException();
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.Unauthorized,
                    authorizationTokenExpiredException.Message,
                    authorizationTokenExpiredException);
                return;
            }

            try
            {
                var usernameObj = principal.Claims.Where(c => c.Type == Database.Username).Single();


                var appnameObj = principal.Claims.Where(c => c.Type == Database.AppName).Single();

                var infoObj = principal.Claims.Where(c => c.Type == Database.TokenInfo).SingleOrDefault();

                if (usernameObj == null)
                {
                    HandleUnauthorized(actionContext, null, null);
                    return;
                }

                if (appnameObj == null)
                {
                    HandleUnauthorized(actionContext, null, null);
                    return;
                }

                string username         = usernameObj.Value;
                string appname          = appnameObj.Value;
                string appNameFromToken = appnameObj.Value;
                bool   mainAppFromToken = appNameFromToken == Maps.DuradosAppName;

                string appNameInHeader = null;
                if (actionContext.Request.Headers.Contains("AppName"))
                {
                    appNameInHeader = actionContext.Request.Headers.GetValues("AppName").FirstOrDefault();
                }
                else if (actionContext.Request.Headers.Contains("appName"))
                {
                    appNameInHeader = actionContext.Request.Headers.GetValues("appName").FirstOrDefault();
                }
                else if (actionContext.Request.Headers.Contains("appname"))
                {
                    appNameInHeader = actionContext.Request.Headers.GetValues("appname").FirstOrDefault();
                }

                Durados.Web.Mvc.Controllers.AccountMembershipService accountMembershipService = new Durados.Web.Mvc.Controllers.AccountMembershipService();

                if (appNameInHeader != null)
                {
                    if (appname.ToLower() == Maps.DuradosAppName)
                    {
                        appname = appNameInHeader;
                    }
                    else
                    {
                        if (appname != appNameInHeader)
                        {
                            // BackandSSO
                            if (!IsSso(appname, appNameInHeader))
                            {
                                actionContext.Response = actionContext.Request.CreateErrorResponse(
                                    HttpStatusCode.Unauthorized,
                                    string.Format(Durados.Web.Mvc.UI.Helpers.UserValidationErrorMessages.AccessTokenNotAllowedToApp, appNameInHeader));
                                return;
                            }
                            else
                            {
                                appname = appNameInHeader;
                                if (!System.Web.HttpContext.Current.Items.Contains(Database.AppName))
                                {
                                    System.Web.HttpContext.Current.Items.Add(Database.AppName, appname);
                                }
                                else
                                {
                                    System.Web.HttpContext.Current.Items[Database.AppName] = appname;
                                }
                                if (!accountMembershipService.IsApproved(username))
                                {
                                    try
                                    {
                                        userController uc          = new userController();
                                        string         provider    = GetDomainControllerProvider(appname);
                                        var            userRow     = (DataRow)GetUserRow(appnameObj.Value, username);
                                        string         socialId    = GetSocialId(provider, username, appnameObj.Value);
                                        bool           hasSocialId = socialId != null;
                                        string         password    = GetPassword();
                                        System.Web.HttpContext.Current.Items.Add(Database.SignupInProcess, true);
                                        if (hasSocialId)
                                        {
                                            uc.SignUpCommand(appname, username, provider, socialId, GetValues(userRow, username), GetFirstName(userRow), GetLastName(userRow), password, true);
                                        }
                                        else
                                        {
                                            bool hasMembership = Maps.Instance.GetMap(appname).GetMembershipProvider().GetUser(username, false) != null;
                                            if (hasMembership)
                                            {
                                                var signUpResults = uc.SignUp(appname, null, null, true, GetFirstName(userRow), username, GetLastName(userRow), password, password, new Dictionary <string, object>());
                                            }
                                            else
                                            {
                                                actionContext.Response = actionContext.Request.CreateErrorResponse(
                                                    HttpStatusCode.Unauthorized,
                                                    string.Format(Durados.Web.Mvc.UI.Helpers.UserValidationErrorMessages.AccessTokenNotAllowedToApp, appNameInHeader));
                                                return;
                                            }
                                        }
                                    }
                                    catch (Exception exception)
                                    {
                                        actionContext.Response = actionContext.Request.CreateErrorResponse(
                                            HttpStatusCode.Unauthorized,
                                            exception.Message,
                                            exception);
                                    }
                                }

                                string key = appname + "_userRow_" + username;

                                System.Web.HttpContext.Current.Items.Remove(key);
                            }
                        }
                    }
                }


                if (!System.Web.HttpContext.Current.Items.Contains(Database.Username))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.Username, username);
                }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.AppName))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.AppName, appname);
                }
                else
                {
                    System.Web.HttpContext.Current.Items[Database.AppName] = appname;
                }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.MainAppFromToken))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.MainAppFromToken, mainAppFromToken);
                }

                string infoJson = null;
                object info     = null;
                if (infoObj != null)
                {
                    infoJson = infoObj.Value;
                    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                    info = jss.Deserialize <Dictionary <string, object> >(infoJson);
                }

                const string ForToken = "forToken";

                IDictionary <string, object> tokenInfo = new Dictionary <string, object>();
                if (info != null && info is IDictionary <string, object> && ((IDictionary <string, object>)info).ContainsKey(ForToken) && ((IDictionary <string, object>)info)[ForToken] is IDictionary <string, object> )
                {
                    tokenInfo = (IDictionary <string, object>)((IDictionary <string, object>)info)[ForToken];
                }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.TokenInfo))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.TokenInfo, tokenInfo);
                }

                try
                {
                    if (SharedMemorySingeltone.Instance.Contains(appname, SharedMemoryKey.DebugMode))
                    {
                        System.Web.HttpContext.Current.Items[Durados.Workflow.JavaScript.Debug] = true;
                    }
                }
                catch { }

                if (!System.Web.HttpContext.Current.Items.Contains(Database.RequestId))
                {
                    System.Web.HttpContext.Current.Items.Add(Database.RequestId, Guid.NewGuid().ToString());
                }
                //NewRelic.Api.Agent.NewRelic.AddCustomParameter(Durados.Database.RequestId, System.Web.HttpContext.Current.Items[Database.RequestId].ToString());
                //if (actionContext.Request.Headers.Contains("AppName"))
                //{
                try
                {
                    //if (!IsAppReady())
                    //{
                    //    throw new Durados.DuradosException("App is not ready yet");
                    //}
                    //if (!accountMembershipService.ValidateUser(username) || !accountMembershipService.IsApproved(username) || Revoked(appname, GetAuthToken(actionContext)))
                    if (!accountMembershipService.IsApproved(username) || Revoked(appname, GetAuthToken(actionContext)))
                    {
                        HandleUnauthorized(actionContext, appname, username);
                        return;
                    }

                    if (!(Maps.IsDevUser(username) || System.Web.HttpContext.Current.Request.Url.Segments.Contains("general/")) && (new Durados.Web.Mvc.UI.Helpers.DuradosAuthorizationHelper().IsAppLocked(appname) || IsAdminLocked(appname, appNameFromToken, username)))
                    {
                        actionContext.Response = actionContext.Request.CreateErrorResponse(
                            HttpStatusCode.Unauthorized,
                            string.Format(Durados.Web.Mvc.UI.Helpers.UserValidationErrorMessages.AppLocked, appname));
                        return;
                    }
                }
                catch (Durados.Web.Mvc.UI.Helpers.AppNotReadyException exception)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(
                        HttpStatusCode.NoContent,
                        exception.Message);
                    return;
                }
                catch (Exception exception)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.InternalServerError,
                        string.Format(Messages.Unexpected, exception.Message));

                    try
                    {
                        Maps.Instance.DuradosMap.Logger.Log(actionContext.ControllerContext.Controller.GetType().Name, actionContext.Request.RequestUri.ToString(), "BackAndAuthorizeAttribute", exception, 1, "authorization failure");
                    }
                    catch { }

                    try
                    {
                        if (Maps.Instance.AppInCach(appname))
                        {
                            Durados.Web.Mvc.UI.Helpers.RestHelper.Refresh(appname);
                        }
                    }
                    catch { }
                    return;
                }
                //}
                if (_allowedRoles == "Admin")
                {
                    string userRole = Maps.Instance.GetMap(appname).Database.GetUserRole();
                    if (!(userRole == "Admin" || userRole == "Developer"))
                    {
                        actionContext.ActionArguments.Add(Database.backand_serverAuthorizationAttempt, true);
                        actionContext.ActionArguments.Add(UserRoleNotSufficient, true);

                        HandleUnauthorized(actionContext, appname, username);
                        return;
                    }
                }
                if (_allowedRoles == "Developer")
                {
                    string userRole = Maps.Instance.GetMap(appname).Database.GetUserRole();
                    if (userRole != "Developer")
                    {
                        actionContext.ActionArguments.Add(Database.backand_serverAuthorizationAttempt, true);
                        actionContext.ActionArguments.Add(UserRoleNotSufficient, true);

                        HandleUnauthorized(actionContext, appname, username);
                        return;
                    }
                }
                try
                {
                    string message = null;
                    if (!mainAppFromToken && IsCustomDeny(appname, username, out message))
                    {
                        HandleUnauthorized(actionContext, appname, username, message);
                        return;
                    }
                }
                catch (Exception exception)
                {
                    HandleUnauthorized(actionContext, appname, username, "Unexpected error: " + exception.Message);
                    return;
                }
                ((apiController)actionContext.ControllerContext.Controller).Init();
            }
            catch
            {
                HandleUnauthorized(actionContext, null, null);
                return;
            }
        }