You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1 line
242 KiB
1 line
242 KiB
angular.module("bit",["ui.router","ngMessages","angular-jwt","ui.bootstrap.showErrors","toastr","angulartics","angular-promise-polyfill","bit.directives","bit.filters","bit.services","bit.global","bit.accounts","bit.vault","bit.settings","bit.tools","bit.organization","bit.reports"]),angular.module("bit").constant("appSettings",{apiUri:"/api",identityUri:"/identity",iconsUri:"/icons",stripeKey:"",braintreeKey:"",selfHosted:!1,version:"1.24.0",environment:"Production"}),angular.module("bit.accounts",["ui.bootstrap","ngCookies"]),angular.module("bit.directives",[]),angular.module("bit.global",[]),angular.module("bit.filters",[]),angular.module("bit.organization",["ui.bootstrap"]),angular.module("bit.reports",["toastr","ngSanitize"]),angular.module("bit.services",["ngResource","ngStorage","angular-jwt"]),angular.module("bit.settings",["ui.bootstrap","toastr"]),angular.module("bit.tools",["ui.bootstrap","toastr"]),angular.module("bit.vault",["ui.bootstrap","ngclipboard"]),angular.module("bit").factory("apiInterceptor",["$injector","$q","toastr","appSettings","utilsService",function(e,t,n,r,o){return{request:function(e){return 0===e.url.indexOf(r.apiUri+"/")&&(e.headers["Device-Type"]=o.getDeviceType()),e},response:function(r){return 401!==r.status&&403!==r.status||(e.get("authService").logOut(),e.get("$state").go("frontend.login.info").then(function(){n.warning("Your login session has expired.","Logged out")})),r||t.when(r)},responseError:function(r){return 401!==r.status&&403!==r.status||(e.get("authService").logOut(),e.get("$state").go("frontend.login.info").then(function(){n.warning("Your login session has expired.","Logged out")})),t.reject(r)}}}]),angular.module("bit").config(["$stateProvider","$urlRouterProvider","$httpProvider","jwtInterceptorProvider","jwtOptionsProvider","$uibTooltipProvider","toastrConfig","$locationProvider","$qProvider","appSettings",function(e,t,n,r,o,a,i,s,l,c){var u;angular.extend(c,window.bitwardenAppSettings),l.errorOnUnhandledRejections(!1),s.hashPrefix(""),o.config({whiteListedDomains:["localhost","api.bitwarden.com","vault.bitwarden.com","haveibeenpwned.com"]}),r.tokenGetter=["options","tokenService","authService",function(e,t,n){if(0===e.url.indexOf(c.apiUri+"/")){if(u)return u;var r=t.getToken();if(r){if(!t.tokenNeedsRefresh(r))return r;var o=n.refreshAccessToken();if(o)return u=o.then(function(e){return u=null,e||r})}}}],angular.extend(i,{closeButton:!0,progressBar:!0,showMethod:"slideDown",target:".toast-target"}),a.options({popupDelay:600,appendToBody:!0}),(-1!==navigator.userAgent.indexOf("MSIE")||navigator.appVersion.indexOf("Trident/")>0)&&(n.defaults.headers.get||(n.defaults.headers.get={}),n.defaults.headers.get["Cache-Control"]="no-cache",n.defaults.headers.get.Pragma="no-cache"),n.interceptors.push("apiInterceptor"),n.interceptors.push("jwtInterceptor"),t.otherwise("/"),e.state("backend",{templateUrl:"app/views/backendLayout.html",abstract:!0,data:{authorize:!0}}).state("backend.user",{templateUrl:"app/views/userLayout.html",abstract:!0}).state("backend.user.vault",{url:"^/vault",templateUrl:"app/vault/views/vault.html",controller:"vaultController",data:{pageTitle:"My Vault",controlSidebar:!0},params:{refreshFromServer:!1}}).state("backend.user.settings",{url:"^/settings",templateUrl:"app/settings/views/settings.html",controller:"settingsController",data:{pageTitle:"Settings"}}).state("backend.user.settingsDomains",{url:"^/settings/domains",templateUrl:"app/settings/views/settingsDomains.html",controller:"settingsDomainsController",data:{pageTitle:"Domain Settings"}}).state("backend.user.settingsTwoStep",{url:"^/settings/two-step",templateUrl:"app/settings/views/settingsTwoStep.html",controller:"settingsTwoStepController",data:{pageTitle:"Two-step Login"}}).state("backend.user.settingsCreateOrg",{url:"^/settings/create-organization",templateUrl:"app/settings/views/settingsCreateOrganization.html",controller:"settingsCreateOrganizationController",data:{pageTitle:"Create Organization"}}).state("backend.user.settingsBilling",{url:"^/settings/billing",templateUrl:"app/settings/views/settingsBilling.html",controller:"settingsBillingController",data:{pageTitle:"Billing"}}).state("backend.user.settingsPremium",{url:"^/settings/premium",templateUrl:"app/settings/views/settingsPremium.html",controller:"settingsPremiumController",data:{pageTitle:"Go Premium"}}).state("backend.user.tools",{url:"^/tools",templateUrl:"app/tools/views/tools.html",controller:"toolsController",data:{pageTitle:"Tools"}}).state("backend.user.reportsBreach",{url:"^/reports/breach",templateUrl:"app/reports/views/reportsBreach.html",controller:"reportsBreachController",data:{pageTitle:"Data Breach Report"}}).state("backend.org",{templateUrl:"app/views/organizationLayout.html",abstract:!0}).state("backend.org.dashboard",{url:"^/organization/:orgId",templateUrl:"app/organization/views/organizationDashboard.html",controller:"organizationDashboardController",data:{pageTitle:"Organization Dashboard"}}).state("backend.org.people",{url:"/organization/:orgId/people?viewEvents&search",templateUrl:"app/organization/views/organizationPeople.html",controller:"organizationPeopleController",data:{pageTitle:"Organization People"}}).state("backend.org.collections",{url:"/organization/:orgId/collections?search",templateUrl:"app/organization/views/organizationCollections.html",controller:"organizationCollectionsController",data:{pageTitle:"Organization Collections"}}).state("backend.org.settings",{url:"/organization/:orgId/settings",templateUrl:"app/organization/views/organizationSettings.html",controller:"organizationSettingsController",data:{pageTitle:"Organization Settings"}}).state("backend.org.billing",{url:"/organization/:orgId/billing",templateUrl:"app/organization/views/organizationBilling.html",controller:"organizationBillingController",data:{pageTitle:"Organization Billing"}}).state("backend.org.vault",{url:"/organization/:orgId/vault?viewEvents&search",templateUrl:"app/organization/views/organizationVault.html",controller:"organizationVaultController",data:{pageTitle:"Organization Vault",controlSidebar:!0}}).state("backend.org.groups",{url:"/organization/:orgId/groups?search",templateUrl:"app/organization/views/organizationGroups.html",controller:"organizationGroupsController",data:{pageTitle:"Organization Groups"}}).state("backend.org.events",{url:"/organization/:orgId/events",templateUrl:"app/organization/views/organizationEvents.html",controller:"organizationEventsController",data:{pageTitle:"Organization Events"}}).state("frontend",{templateUrl:"app/views/frontendLayout.html",abstract:!0,data:{authorize:!1}}).state("frontend.login",{templateUrl:"app/accounts/views/accountsLogin.html",controller:"accountsLoginController",params:{returnState:null,email:null,premium:null,org:null},data:{bodyClass:"login-page"}}).state("frontend.login.info",{url:"^/?org&premium&email",templateUrl:"app/accounts/views/accountsLoginInfo.html",data:{pageTitle:"Log In"}}).state("frontend.login.twoFactor",{url:"^/two-step?org&premium&email",templateUrl:"app/accounts/views/accountsLoginTwoFactor.html",data:{pageTitle:"Log In (Two-step)"}}).state("frontend.logout",{url:"^/logout",controller:"accountsLogoutController",data:{authorize:!0}}).state("frontend.passwordHint",{url:"^/password-hint",templateUrl:"app/accounts/views/accountsPasswordHint.html",controller:"accountsPasswordHintController",data:{pageTitle:"Master Password Hint",bodyClass:"login-page"}}).state("frontend.recover",{url:"^/recover",templateUrl:"app/accounts/views/accountsRecover.html",controller:"accountsRecoverController",data:{pageTitle:"Recover Account",bodyClass:"login-page"}}).state("frontend.recover-delete",{url:"^/recover-delete",templateUrl:"app/accounts/views/accountsRecoverDelete.html",controller:"accountsRecoverDeleteController",data:{pageTitle:"Delete Account",bodyClass:"login-page"}}).state("frontend.verify-recover-delete",{url:"^/verify-recover-delete?userId&token&email",templateUrl:"app/accounts/views/accountsVerifyRecoverDelete.html",controller:"accountsVerifyRecoverDeleteController",data:{pageTitle:"Confirm Delete Account",bodyClass:"login-page"}}).state("frontend.register",{url:"^/register?org&premium",templateUrl:"app/accounts/views/accountsRegister.html",controller:"accountsRegisterController",params:{returnState:null,email:null,org:null,premium:null},data:{pageTitle:"Register",bodyClass:"register-page"}}).state("frontend.organizationAccept",{url:"^/accept-organization?organizationId&organizationUserId&token&email&organizationName",templateUrl:"app/accounts/views/accountsOrganizationAccept.html",controller:"accountsOrganizationAcceptController",data:{pageTitle:"Accept Organization Invite",bodyClass:"login-page",skipAuthorize:!0}}).state("frontend.verifyEmail",{url:"^/verify-email?userId&token",templateUrl:"app/accounts/views/accountsVerifyEmail.html",controller:"accountsVerifyEmailController",data:{pageTitle:"Verifying Email",bodyClass:"login-page",skipAuthorize:!0}})}]).run(["$rootScope","authService","$state",function(e,t,n){e.$on("$stateChangeSuccess",function(){$("html, body").animate({scrollTop:0},200)}),e.$on("$stateChangeStart",function(r,o,a){if(!o.data||!o.data.authorize){if(o.data&&o.data.skipAuthorize)return;if(!t.isAuthenticated())return;return r.preventDefault(),void n.go("backend.user.vault")}if(!t.isAuthenticated())return r.preventDefault(),t.logOut(),void n.go("frontend.login.info");o.name.indexOf("backend.org.")>-1&&a.orgId&&(e.vaultCiphers=e.vaultFolders=e.vaultCollections=null,t.getUserProfile().then(function(e){var t=e.organizations;t&&a.orgId in t&&2===t[a.orgId].status&&2!==t[a.orgId].type||(r.preventDefault(),n.go("backend.user.vault"))}))})}]),angular.module("bit").constant("constants",{rememberedEmailCookieName:"bit.rememberedEmail",encType:{AesCbc256_B64:0,AesCbc128_HmacSha256_B64:1,AesCbc256_HmacSha256_B64:2,Rsa2048_OaepSha256_B64:3,Rsa2048_OaepSha1_B64:4,Rsa2048_OaepSha256_HmacSha256_B64:5,Rsa2048_OaepSha1_HmacSha256_B64:6},orgUserType:{owner:0,admin:1,user:2},orgUserStatus:{invited:0,accepted:1,confirmed:2},twoFactorProvider:{u2f:4,yubikey:3,duo:2,authenticator:0,email:1,remember:5},cipherType:{login:1,secureNote:2,card:3,identity:4},fieldType:{text:0,hidden:1,boolean:2},deviceType:{android:0,ios:1,chromeExt:2,firefoxExt:3,operaExt:4,edgeExt:5,windowsDesktop:6,macOsDesktop:7,linuxDesktop:8,chrome:9,firefox:10,opera:11,edge:12,ie:13,unknown:14,uwp:16,safari:17,vivaldi:18,vivaldiExt:19},eventType:{User_LoggedIn:1e3,User_ChangedPassword:1001,User_Enabled2fa:1002,User_Disabled2fa:1003,User_Recovered2fa:1004,User_FailedLogIn:1005,User_FailedLogIn2fa:1006,Cipher_Created:1100,Cipher_Updated:1101,Cipher_Deleted:1102,Cipher_AttachmentCreated:1103,Cipher_AttachmentDeleted:1104,Cipher_Shared:1105,Cipher_UpdatedCollections:1106,Collection_Created:1300,Collection_Updated:1301,Collection_Deleted:1302,Group_Created:1400,Group_Updated:1401,Group_Deleted:1402,OrganizationUser_Invited:1500,OrganizationUser_Confirmed:1501,OrganizationUser_Updated:1502,OrganizationUser_Removed:1503,OrganizationUser_UpdatedGroups:1504,Organization_Updated:1600},twoFactorProviderInfo:[{type:0,name:"Authenticator App",description:"Use an authenticator app (such as Authy or Google Authenticator) to generate time-based verification codes.",enabled:!1,active:!0,free:!0,image:"authapp.png",displayOrder:0,priority:1,requiresUsb:!1},{type:3,name:"YubiKey OTP Security Key",description:"Use a YubiKey to access your account. Works with YubiKey 4, 4 Nano, 4C, and NEO devices.",enabled:!1,active:!0,image:"yubico.png",displayOrder:1,priority:3,requiresUsb:!0},{type:2,name:"Duo",description:"Verify with Duo Security using the Duo Mobile app, SMS, phone call, or U2F security key.",enabled:!1,active:!0,image:"duo.png",displayOrder:2,priority:2,requiresUsb:!1},{type:4,name:"FIDO U2F Security Key",description:"Use any FIDO U2F enabled security key to access your account.",enabled:!1,active:!0,image:"fido.png",displayOrder:3,priority:4,requiresUsb:!0},{type:1,name:"Email",description:"Verification codes will be emailed to you.",enabled:!1,active:!0,free:!0,image:"gmail.png",displayOrder:4,priority:0,requiresUsb:!1}],plans:{free:{basePrice:0,noAdditionalSeats:!0,noPayment:!0,upgradeSortOrder:-1},families:{basePrice:1,annualBasePrice:12,baseSeats:5,noAdditionalSeats:!0,annualPlanType:"familiesAnnually",upgradeSortOrder:1},teams:{basePrice:5,annualBasePrice:60,monthlyBasePrice:8,baseSeats:5,seatPrice:2,annualSeatPrice:24,monthlySeatPrice:2.5,monthPlanType:"teamsMonthly",annualPlanType:"teamsAnnually",upgradeSortOrder:2},enterprise:{seatPrice:3,annualSeatPrice:36,monthlySeatPrice:4,monthPlanType:"enterpriseMonthly",annualPlanType:"enterpriseAnnually",upgradeSortOrder:3}},storageGb:{price:.33,monthlyPrice:.5,yearlyPrice:4},premium:{price:10,yearlyPrice:10}}),angular.module("bit.accounts").controller("accountsLoginController",["$scope","$rootScope","$cookies","apiService","cryptoService","authService","$state","constants","$analytics","$uibModal","$timeout","$window","$filter","toastr",function(e,t,n,r,o,a,i,s,l,c,u,d,p,m){e.state=i,e.twoFactorProviderConstants=s.twoFactorProvider,e.rememberTwoFactor={checked:!1};var g=!0;e.returnState=i.params.returnState,e.stateEmail=i.params.email,!e.returnState&&i.params.org?e.returnState={name:"backend.user.settingsCreateOrg",params:{plan:i.params.org}}:!e.returnState&&i.params.premium&&(e.returnState={name:"backend.user.settingsPremium"}),!(i.current.name.indexOf("twoFactor")>-1)||e.twoFactorProviders&&e.twoFactorProviders.length||i.go("frontend.login.info",{returnState:e.returnState});var f,h,v=n.get(s.rememberedEmailCookieName);function y(){e.returnState?i.go(e.returnState.name,e.returnState.params):i.go("backend.user.vault")}function b(){var t;if(g=!0,e.twoFactorProvider===s.twoFactorProvider.duo)t=e.twoFactorProviders[s.twoFactorProvider.duo],d.Duo.init({host:t.Host,sig_request:t.Signature,submit_callback:function(t){var n=$(t).find('input[name="sig_response"]').val();e.twoFactor(n)}});else if(e.twoFactorProvider===s.twoFactorProvider.u2f){g=!1,t=e.twoFactorProviders[s.twoFactorProvider.u2f],function t(n){if(g)return;if(n.length<1||e.twoFactorProvider!==s.twoFactorProvider.u2f)return;console.log("listening for u2f key...");d.u2f.sign(n[0].appId,n[0].challenge,[{version:n[0].version,keyHandle:n[0].keyHandle}],function(r){if(e.twoFactorProvider===s.twoFactorProvider.u2f)return r.errorCode?(console.log(r.errorCode),void u(function(){t(n)},5===r.errorCode?0:1e3)):void e.twoFactor(JSON.stringify(r))},10)}(JSON.parse(t.Challenges))}else e.twoFactorProvider===s.twoFactorProvider.email&&(t=e.twoFactorProviders[s.twoFactorProvider.email],e.twoFactorEmail=t.Email,Object.keys(e.twoFactorProviders).length>1&&e.sendEmail(!1))}v||e.stateEmail?(e.model={email:e.stateEmail||v,rememberEmail:null!==v},u(function(){$("#masterPassword").focus()})):u(function(){$("#email").focus()}),e.twoFactorProviders=null,e.twoFactorProvider=null,e.login=function(t){e.loginPromise=a.logIn(t.email,t.masterPassword).then(function(r){if(t.rememberEmail){var o=new Date;o.setFullYear(o.getFullYear()+10),n.put(s.rememberedEmailCookieName,t.email,{expires:o})}else n.remove(s.rememberedEmailCookieName);r&&Object.keys(r).length>0?(f=t.email,h=t.masterPassword,e.twoFactorProviders=function(e){if(t=!1,n=navigator.userAgent||navigator.vendor||window.opera,(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(n)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(n.substr(0,4)))&&(t=!0),!t&&!navigator.userAgent.match(/iPad/i))return e;var t,n;for(var r=Object.keys(e),o=0;o<r.length;o++){var a=p("filter")(s.twoFactorProviderInfo,{type:r[o],active:!0,requiresUsb:!1});a.length||delete e[r[o]]}return e}(r),e.twoFactorProvider=function(e){for(var t=Object.keys(e),n=null,r=-1,o=0;o<t.length;o++){var a=p("filter")(s.twoFactorProviderInfo,{type:t[o],active:!0});if(a.length&&a[0].priority>r){if(a[0].type===s.twoFactorProvider.u2f&&!u2f.isSupported)continue;n=a[0].type,r=a[0].priority}}if(null===n)return null;return parseInt(n)}(e.twoFactorProviders),l.eventTrack("Logged In To Two-step"),i.go("frontend.login.twoFactor",{returnState:e.returnState}).then(function(){u(function(){$("#code").focus(),b()})})):(l.eventTrack("Logged In"),y()),t.masterPassword=""})},e.twoFactor=function(t){e.twoFactorProvider!==s.twoFactorProvider.email&&e.twoFactorProvider!==s.twoFactorProvider.authenticator||(t=t.replace(" ","")),e.twoFactorPromise=a.logIn(f,h,t,e.twoFactorProvider,e.rememberTwoFactor.checked||!1),e.twoFactorPromise.then(function(){l.eventTrack("Logged In From Two-step"),y()},function(){e.twoFactorProvider===s.twoFactorProvider.u2f&&b()})},e.anotherMethod=function(){c.open({animation:!0,templateUrl:"app/accounts/views/accountsTwoFactorMethods.html",controller:"accountsTwoFactorMethodsController",resolve:{providers:function(){return e.twoFactorProviders}}}).result.then(function(t){e.twoFactorProvider=t,u(function(){$("#code").focus(),b()})})},e.sendEmail=function(t){if(e.twoFactorProvider===s.twoFactorProvider.email)return o.makeKeyAndHash(f,h).then(function(e){return r.twoFactor.sendEmailLogin({email:f,masterPasswordHash:e.hash}).$promise}).then(function(){t&&m.success("Verification email sent to "+e.twoFactorEmail+".")},function(){m.error("Could not send verification email.")})},e.$on("$destroy",function(){g=!0})}]),angular.module("bit.accounts").controller("accountsLogoutController",["$scope","authService","$state","$analytics",function(e,t,n,r){t.logOut(),r.eventTrack("Logged Out"),n.go("frontend.login.info")}]),angular.module("bit.accounts").controller("accountsOrganizationAcceptController",["$scope","$state","apiService","authService","toastr","$analytics",function(e,t,n,r,o,a){e.state={name:t.current.name,params:t.params},t.params.organizationId&&t.params.organizationUserId&&t.params.token&&t.params.email&&t.params.organizationName?e.$on("$viewContentLoaded",function(){r.isAuthenticated()?(e.accepting=!0,n.organizationUsers.accept({orgId:t.params.organizationId,id:t.params.organizationUserId},{token:t.params.token},function(){a.eventTrack("Accepted Invitation"),t.go("backend.user.vault",null,{location:"replace"}).then(function(){o.success("You can access this organization once an administrator confirms your membership. We'll send an email when that happens.","Invite Accepted",{timeOut:1e4})})},function(){a.eventTrack("Failed To Accept Invitation"),t.go("backend.user.vault",null,{location:"replace"}).then(function(){o.error("Unable to accept invitation.","Error")})})):e.loading=!1}):t.go("frontend.login.info").then(function(){o.error("Invalid parameters.")})}]),angular.module("bit.accounts").controller("accountsPasswordHintController",["$scope","$rootScope","apiService","$analytics",function(e,t,n,r){e.success=!1,e.submit=function(t){e.submitPromise=n.accounts.postPasswordHint({email:t.email},function(){r.eventTrack("Requested Password Hint"),e.success=!0}).$promise}}]),angular.module("bit.accounts").controller("accountsRecoverController",["$scope","apiService","cryptoService","$analytics",function(e,t,n,r){e.success=!1,e.submit=function(o){var a=o.email.toLowerCase();e.submitPromise=n.makeKeyAndHash(o.email,o.masterPassword).then(function(e){return t.twoFactor.recover({email:a,masterPasswordHash:e.hash,recoveryCode:o.code.replace(/\s/g,"").toLowerCase()}).$promise}).then(function(){r.eventTrack("Recovered 2FA"),e.success=!0})}}]),angular.module("bit.accounts").controller("accountsRecoverDeleteController",["$scope","$rootScope","apiService","$analytics",function(e,t,n,r){e.success=!1,e.submit=function(t){e.submitPromise=n.accounts.postDeleteRecover({email:t.email},function(){r.eventTrack("Started Delete Recovery"),e.success=!0}).$promise}}]),angular.module("bit.accounts").controller("accountsRegisterController",["$scope","$location","apiService","cryptoService","validationService","$analytics","$state","$timeout",function(e,t,n,r,o,a,i,s){var l=t.search(),c=i.params;e.createOrg=c.org,!c.returnState&&c.org?e.returnState={name:"backend.user.settingsCreateOrg",params:{plan:i.params.org}}:!c.returnState&&c.premium?e.returnState={name:"backend.user.settingsPremium",params:{plan:i.params.org}}:e.returnState=c.returnState,e.success=!1,e.model={email:l.email?l.email:c.email},e.readOnlyEmail=null!==c.email,s(function(){e.model.email?$("#name").focus():$("#email").focus()}),e.registerPromise=null,e.register=function(t){var i=!1;if(e.model.masterPassword.length<8&&(o.addError(t,"MasterPassword","Master password must be at least 8 characters long.",!0),i=!0),e.model.masterPassword!==e.model.confirmMasterPassword&&(o.addError(t,"ConfirmMasterPassword","Master password confirmation does not match.",!0),i=!0),!i){var s,l,c=e.model.email.toLowerCase();e.registerPromise=r.makeKeyAndHash(c,e.model.masterPassword).then(function(e){return s=e,l=r.makeEncKey(e.key),r.makeKeyPair(l.encKey)}).then(function(t){var r={name:e.model.name,email:c,masterPasswordHash:s.hash,masterPasswordHint:e.model.masterPasswordHint,key:l.encKeyEnc,keys:{publicKey:t.publicKey,encryptedPrivateKey:t.privateKeyEnc}};return n.accounts.register(r).$promise},function(e){return o.addError(t,null,"Problem generating keys.",!0),!1}).then(function(t){!1!==t&&(e.success=!0,a.eventTrack("Registered"))})}}}]),angular.module("bit.accounts").controller("accountsTwoFactorMethodsController",["$scope","$uibModalInstance","$analytics","providers","constants",function(e,t,n,r,o){function a(t){for(var n=0;n<o.twoFactorProviderInfo.length;n++)o.twoFactorProviderInfo[n].type===t&&e.providers.push(o.twoFactorProviderInfo[n])}n.eventTrack("accountsTwoFactorMethodsController",{category:"Modal"}),e.providers=[],r.hasOwnProperty(o.twoFactorProvider.authenticator)&&a(o.twoFactorProvider.authenticator),r.hasOwnProperty(o.twoFactorProvider.yubikey)&&a(o.twoFactorProvider.yubikey),r.hasOwnProperty(o.twoFactorProvider.email)&&a(o.twoFactorProvider.email),r.hasOwnProperty(o.twoFactorProvider.duo)&&a(o.twoFactorProvider.duo),r.hasOwnProperty(o.twoFactorProvider.u2f)&&u2f.isSupported&&a(o.twoFactorProvider.u2f),e.choose=function(e){t.close(e.type)},e.close=function(){t.dismiss("close")}}]),angular.module("bit.accounts").controller("accountsVerifyEmailController",["$scope","$state","apiService","toastr","$analytics",function(e,t,n,r,o){t.params.userId&&t.params.token?e.$on("$viewContentLoaded",function(){n.accounts.verifyEmailToken({},{token:t.params.token,userId:t.params.userId},function(){o.eventTrack("Verified Email"),t.go("frontend.login.info",null,{location:"replace"}).then(function(){r.success("Your email has been verified. Thank you.","Success")})},function(){t.go("frontend.login.info",null,{location:"replace"}).then(function(){r.error("Unable to verify email.","Error")})})}):t.go("frontend.login.info").then(function(){r.error("Invalid parameters.")})}]),angular.module("bit.accounts").controller("accountsVerifyRecoverDeleteController",["$scope","$state","apiService","toastr","$analytics",function(e,t,n,r,o){t.params.userId&&t.params.token&&t.params.email?(e.email=t.params.email,e.delete=function(){confirm("Are you sure you want to delete this account? This cannot be undone.")&&(e.deleting=!0,n.accounts.postDeleteRecoverToken({},{token:t.params.token,userId:t.params.userId},function(){o.eventTrack("Recovered Delete"),t.go("frontend.login.info",null,{location:"replace"}).then(function(){r.success("Your account has been deleted. You can register a new account again if you like.","Success")})},function(){t.go("frontend.login.info",null,{location:"replace"}).then(function(){r.error("Unable to delete account.","Error")})}))}):t.go("frontend.login.info").then(function(){r.error("Invalid parameters.")})}]),angular.module("bit.directives").directive("apiField",function(){var e=function(e,t,n,r){r.$registerApiError=function(){r.$setValidity("api",!1)},r.$validators.apiValidate=function(){return r.$setValidity("api",!0),!0}};return{require:"ngModel",restrict:"A",compile:function(t,n){if(!n.name||""===n.name)throw"api-field element does not have a valid name attribute";return e}}}),angular.module("bit.directives").directive("apiForm",["$rootScope","validationService","$timeout",function(e,t,n){return{require:"form",restrict:"A",link:function(e,r,o,a){var i=o.apiForm||null;void 0!==i&&e.$watch(i,function(e,r,o){if(!o||!o.then)return;e.$errors=null,e.$loading=!0,o.then(function(t){n(function(){e.$loading=!1})},function(o){n(function(){e.$loading=!1,"string"==typeof o?t.addError(e,null,o,!0):t.addErrors(e,o),r.$broadcast("show-errors-check-validity"),$("html, body").animate({scrollTop:0},200)})})}.bind(null,a,e))}}}]),angular.module("bit.directives").directive("fallbackSrc",function(){return function(e,t,n){var r=$(t);r.bind("error",function(e){r.attr("src",n.fallbackSrc)})}}),angular.module("bit.directives").directive("letterAvatar",function(){return{restrict:"AE",replace:!0,scope:{data:"@"},link:function(e,t,n){var r={charCount:n.charcount||2,data:n.data,textColor:n.textcolor||"#ffffff",bgColor:n.bgcolor,height:n.avheight||45,width:n.avwidth||45,fontSize:n.fontsize||20,fontWeight:n.fontweight||300,fontFamily:n.fontfamily||"Open Sans, HelveticaNeue-Light, Helvetica Neue Light, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif",round:n.round||"true",dynamic:n.dynamic||"true",class:n.avclass||"",border:n.avborder||"false",borderStyle:n.borderstyle||"3px solid white"};function o(){var n=null,o=e.data.toUpperCase();r.charCount>1&&(n=function(e,t){var n=e.split(" ");if(n&&n.length>1){for(var r="",o=0;o<t;o++)r+=n[o].substr(0,1);return r}return null}(o,r.charCount)),n||(n=o.substr(0,r.charCount));var a,i,s,l,c,u,d,p,m=(a=n,i=r.textColor,s=r.fontFamily,l=r.fontWeight,c=r.fontSize,angular.element('<text text-anchor="middle"></text>').attr({y:"50%",x:"50%",dy:"0.35em","pointer-events":"auto",fill:i,"font-family":s}).text(a).css({"font-weight":l,"font-size":c+"px"})),g=r.bgColor?r.bgColor:function(e){var t=0,n=0;for(n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);var r="#";for(n=0;n<3;n++)r+=("00"+(t>>8*n&255).toString(16)).substr(-2);return r}(o),f=(u=r.width,d=r.height,p=g,angular.element("<svg></svg>").attr({xmlns:"http://www.w3.org/2000/svg","pointer-events":"none",width:u,height:d}).css({"background-color":p,width:u+"px",height:d+"px"}));f.append(m);var h=angular.element("<div>").append(f).html(),v="data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(h))),y=angular.element("<img>").attr({src:v,title:e.data});"true"===r.round&&y.css("border-radius","50%"),"true"===r.border&&y.css("border",r.borderStyle),r.class&&y.addClass(r.class),"true"===r.dynamic?(t.empty(),t.append(y)):t.replaceWith(y)}"true"===r.dynamic?e.$watch("data",function(){o()}):o()}}}),angular.module("bit.directives").directive("masterPassword",["cryptoService","authService",function(e,t){return{require:"ngModel",restrict:"A",link:function(n,r,o,a){t.getUserProfile().then(function(t){a.$parsers.unshift(function(n){if(n)return e.makeKey(n,t.email).then(function(t){var r=t.keyB64===e.getKey().keyB64;return a.$setValidity("masterPassword",r),r?n:void 0})}),a.$formatters.unshift(function(n){if(n)return e.makeKey(n,t.email).then(function(t){var r=t.keyB64===e.getKey().keyB64;return a.$setValidity("masterPassword",r),n})})})}}}]),angular.module("bit.directives").directive("pageTitle",["$rootScope","$timeout","appSettings",function(e,t,n){return{link:function(n,r){e.$on("$stateChangeStart",function(e,n,o,a,i){var s="Bitwarden Web Vault";n.data&&n.data.pageTitle&&(s=n.data.pageTitle+" - "+s),t(function(){r.text(s)})})}}}]),angular.module("bit.directives").directive("passwordMeter",function(){return{template:'<div class="progress {{outerClass}}"><div class="progress-bar progress-bar-{{valueClass}}" role="progressbar" aria-valuenow="{{value}}" aria-valuemin="0" aria-valuemax="100" ng-style="{width : ( value + \'%\' ) }"><span class="sr-only">{{value}}%</span></div></div>',restrict:"A",scope:{password:"=passwordMeter",username:"=passwordMeterUsername",outerClass:"@?"},link:function(e){var t=function(e){e.value=function(e,t){if(!t||t===e)return 0;var n=t.length;return e&&""!==e&&(-1!==e.indexOf(t)&&(n-=15),-1!==t.indexOf(e)&&(n-=e.length)),t.length>0&&t.length<=4?n+=t.length:t.length>=5&&t.length<=7?n+=6:t.length>=8&&t.length<=15?n+=12:t.length>=16&&(n+=18),t.match(/[a-z]/)&&(n+=1),t.match(/[A-Z]/)&&(n+=5),t.match(/\d/)&&(n+=5),t.match(/.*\d.*\d.*\d/)&&(n+=5),t.match(/[!,@,#,$,%,^,&,*,?,_,~]/)&&(n+=5),t.match(/.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~]/)&&(n+=5),t.match(/(?=.*[a-z])(?=.*[A-Z])/)&&(n+=2),t.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/)&&(n+=2),t.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!,@,#,$,%,^,&,*,?,_,~])/)&&(n+=2),n=Math.round(2*n),Math.max(0,Math.min(100,n))}(e.username,e.password),e.valueClass=function(e){switch(Math.round(e/33)){case 0:case 1:return"danger";case 2:return"warning";case 3:return"success"}}(e.value)};e.$watch("password",function(){t(e)}),e.$watch("username",function(){t(e)})}}}),angular.module("bit.directives").directive("passwordViewer",function(){return{restrict:"A",link:function(e,t,n){var r=n.passwordViewer;r&&(t.onclick=function(e){},t.on("click",function(e){var n=$(r);n&&"password"===n.attr("type")?(t.removeClass("fa-eye").addClass("fa-eye-slash"),n.attr("type","text")):n&&"text"===n.attr("type")&&(t.removeClass("fa-eye-slash").addClass("fa-eye"),n.attr("type","password"))}))}}}),angular.module("bit.directives").directive("stopClick",function(){return function(e,t,n){$(t).click(function(e){e.preventDefault()})}}),angular.module("bit.directives").directive("stopProp",function(){return function(e,t,n){$(t).click(function(e){e.stopPropagation()})}}),angular.module("bit.directives").directive("totp",["$timeout","$q",function(e,t){return{template:'<div class="totp{{(low ? \' low\' : \'\')}}" ng-if="code"><span class="totp-countdown"><span class="totp-sec">{{sec}}</span><svg><g><circle class="totp-circle inner" r="12.6" cy="16" cx="16" style="stroke-dashoffset: {{dash}}px;"></circle><circle class="totp-circle outer" r="14" cy="16" cx="16"></circle></g></svg></span><span class="totp-code" id="totp-code">{{codeFormatted}}</span><a href="#" stop-click class="btn btn-link" ngclipboard ngclipboard-error="clipboardError(e)" data-clipboard-text="{{code}}" uib-tooltip="Copy Code" tooltip-placement="right"><i class="fa fa-clipboard"></i></a></div>',restrict:"A",scope:{key:"=totp"},link:function(n){var r=null,o=new function(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",n=function(e,t,n){return t+1>=e.length&&(e=Array(t+1-e.length).join(n)+e),e},r=function(e){return parseInt(e,16)},o=function(e){for(var t=new Uint8Array(e.length/2),n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t},a=function(t){return o(function(t){t=t.toUpperCase();var r,o="";for(r=0;r<t.length;r++)e.indexOf(t[r])<0||(o+=t[r]);t=o;var a="",i="";for(r=0;r<t.length;r++){var s=e.indexOf(t.charAt(r));s<0||(a+=n(s.toString(2),5,"0"))}for(r=0;r+4<=a.length;r+=4){var l=a.substr(r,4);i+=parseInt(l,2).toString(16)}return i}(t))},i=function(e,t){return window.crypto.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]).then(function(e){return window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-1"}},e,t)}).then(function(e){return function(e){for(var t=new Uint8Array(e),n=[],r=0;r<t.length;r++)n.push((t[r]>>>4).toString(16)),n.push((15&t[r]).toString(16));return n.join("")}(e)}).catch(function(e){return null})};this.getCode=function(e){var s,l=Math.round((new Date).getTime()/1e3),c=n(((s=Math.floor(l/30))<15.5?"0":"")+Math.round(s).toString(16),16,"0"),u=o(c),d=a(e);return d.length&&u.length?i(d,u).then(function(e){if(!e)return null;var t=r(e.substring(e.length-1)),n=(r(e.substr(2*t,8))&r("7fffffff"))+"";return n=n.substr(n.length-6,6)}):t(function(e,t){e(null)})}},a=function(t){o.getCode(t.key).then(function(n){e(function(){n?(t.codeFormatted=n.substring(0,3)+" "+n.substring(3),t.code=n):(t.code=null,r&&clearInterval(r))})})},i=function(t){e(function(){var e=Math.round((new Date).getTime()/1e3)%30,n=30-e;t.sec=n,t.dash=(2.62*e).toFixed(2),t.low=n<=7,0===e&&a(t)})};n.$watch("key",function(){if(!n.key)return n.code=null,void(r&&clearInterval(r));a(n),i(n),r&&clearInterval(r),r=setInterval(function(){i(n)},1e3)}),n.$on("$destroy",function(){r&&clearInterval(r)}),n.clipboardError=function(e){alert("Your web browser does not support easy clipboard copying.")}}}}]),angular.module("bit.global").controller("mainController",["$scope","$state","authService","appSettings","toastr","$window","$document","cryptoService","$uibModal","apiService",function(e,t,n,r,o,a,i,s,l,c){var u,d,p,m=this;m.skinClass=r.selfHosted?"skin-blue-light":"skin-blue",m.bodyClass="",m.usingControlSidebar=m.openControlSidebar=!1,m.searchVaultText=null,m.version=r.version,m.outdatedBrowser=-1!==a.navigator.userAgent.indexOf("MSIE")||-1!==a.navigator.userAgent.indexOf("SamsungBrowser"),e.currentYear=(new Date).getFullYear(),e.$on("$viewContentLoaded",function(){n.getUserProfile().then(function(e){m.userProfile=e}),$.AdminLTE&&($.AdminLTE.layout&&($.AdminLTE.layout.fix(),$.AdminLTE.layout.fixSidebar()),$.AdminLTE.pushMenu&&$.AdminLTE.pushMenu.expandOnHover(),i.off("click",".sidebar li a"))}),e.$on("$stateChangeSuccess",function(e,t,n,r,o){m.usingEncKey=!!s.getEncKey(),m.searchVaultText=null,t.data.bodyClass?m.bodyClass=t.data.bodyClass:(m.bodyClass="",m.usingControlSidebar=!!t.data.controlSidebar,m.openControlSidebar=m.usingControlSidebar&&i.width()>768)}),e.addCipher=function(){e.$broadcast("vaultAddCipher")},e.addFolder=function(){e.$broadcast("vaultAddFolder")},e.addOrganizationCipher=function(){e.$broadcast("organizationVaultAddCipher")},e.addOrganizationCollection=function(){e.$broadcast("organizationCollectionsAdd")},e.inviteOrganizationUser=function(){e.$broadcast("organizationPeopleInvite")},e.addOrganizationGroup=function(){e.$broadcast("organizationGroupsAdd")},e.updateKey=function(){l.open({animation:!0,templateUrl:"app/settings/views/settingsUpdateKey.html",controller:"settingsUpdateKeyController"})},e.verifyEmail=function(){e.sendingVerify||(e.sendingVerify=!0,c.accounts.verifyEmail({},null).$promise.then(function(){o.success("Verification email sent."),e.sendingVerify=!1,e.verifyEmailSent=!0}).catch(function(){o.success("Verification email failed."),e.sendingVerify=!1}))},e.updateBrowser=function(){a.open("https://browser-update.org/update.html","_blank")};var g={scrollbarWidth:function(){if(!u){var e=$("body");e.addClass("bit-position-body-scrollbar-measure"),u=a.innerWidth-e[0].clientWidth,u=isFinite(u)?u:0,e.removeClass("bit-position-body-scrollbar-measure")}return u},scrollbarInfo:function(){return{width:g.scrollbarWidth(),visible:i.height()>$(a).height()}}};$(window).on("show.bs.dropdown",function(e){var t=p=$(e.target),n=t.data("appendTo");if(!n)return!0;d=t.find(".dropdown-menu"),$(n).append(d.detach());var r=t.offset(),o={display:"block",top:r.top+t.outerHeight()-("body"!==n?$(window).scrollTop():0)};if(d.hasClass("dropdown-menu-right")){var i=g.scrollbarInfo(),s=0;i.visible&&i.width&&(s=i.width),o.right=a.innerWidth-s-(r.left+t.prop("offsetWidth"))+"px",o.left="auto"}else o.left=r.left+"px",o.right="auto";d.css(o)}),$(window).on("hide.bs.dropdown",function(e){if(!d)return!0;$(e.target).append(d.detach()),d.hide(),d=null,p=null}),e.$on("removeAppendedDropdownMenu",function(e,t){if(!d&&!p)return!0;p.append(d.detach()),d.hide(),d=null,p=null})}]),angular.module("bit.global").controller("paidOrgRequiredController",["$scope","$state","$uibModalInstance","$analytics","$uibModalStack","orgId","constants","authService",function(e,t,n,r,o,a,i,s){r.eventTrack("paidOrgRequiredController",{category:"Modal"}),s.getUserProfile().then(function(t){e.admin=t.organizations[a].type!==i.orgUserType.user}),e.go=function(){e.admin&&(r.eventTrack("Get Paid Org"),t.go("backend.org.billing",{orgId:a}).then(function(){o.dismissAll()}))},e.close=function(){n.dismiss("close")}}]),angular.module("bit.global").controller("premiumRequiredController",["$scope","$state","$uibModalInstance","$analytics","$uibModalStack",function(e,t,n,r,o){r.eventTrack("premiumRequiredController",{category:"Modal"}),e.go=function(){r.eventTrack("Get Premium"),t.go("backend.user.settingsPremium").then(function(){o.dismissAll()})},e.close=function(){n.dismiss("close")}}]),angular.module("bit.global").controller("sideNavController",["$scope","$state","authService","toastr","$analytics","constants","appSettings",function(e,t,n,r,o,a,i){e.$state=t,e.params=t.params,e.orgs=[],e.name="",i.selfHosted?(e.orgIconBgColor="#ffffff",e.orgIconBorder="3px solid #a0a0a0",e.orgIconTextColor="#333333"):(e.orgIconBgColor="#2c3b41",e.orgIconBorder="3px solid #1a2226",e.orgIconTextColor="#ffffff"),n.getUserProfile().then(function(n){if(e.name=n.extended&&n.extended.name?n.extended.name:n.email,n.organizations)if(t.includes("backend.org")&&t.params.orgId in n.organizations)e.orgProfile=n.organizations[t.params.orgId];else{var r=[];for(var o in n.organizations)n.organizations.hasOwnProperty(o)&&(n.organizations[o].enabled||n.organizations[o].type<2)&&r.push(n.organizations[o]);e.orgs=r}}),e.viewOrganization=function(e){e.type!==a.orgUserType.user?(o.eventTrack("View Organization From Side Nav"),t.go("backend.org.dashboard",{orgId:e.id})):r.error("You cannot manage this organization.")},e.isOrgOwner=function(e){return e&&e.type===a.orgUserType.owner}}]),angular.module("bit.global").controller("topNavController",["$scope",function(e){e.toggleControlSidebar=function(){var e=$("body");e.hasClass("control-sidebar-open")?e.removeClass("control-sidebar-open"):e.addClass("control-sidebar-open")}}]),angular.module("bit.filters").filter("enumLabelClass",function(){return function(e,t){if("number"!=typeof e)return e.toString();var n;switch(t){case"OrgUserStatus":switch(e){case 0:n="label-default";break;case 1:n="label-warning";break;case 2:default:n="label-success"}break;default:n="label-default"}return n}}),angular.module("bit.filters").filter("enumName",function(){return function(e,t){if("number"!=typeof e)return e.toString();var n;switch(t){case"OrgUserStatus":switch(e){case 0:n="Invited";break;case 1:n="Accepted";break;case 2:default:n="Confirmed"}break;case"OrgUserType":switch(e){case 0:n="Owner";break;case 1:n="Admin";break;case 2:default:n="User"}break;default:n=e.toString()}return n}}),angular.module("bit.organization").controller("organizationBillingAdjustSeatsController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,r,o,a,i){o.eventTrack("organizationBillingAdjustSeatsController",{category:"Modal"}),e.add=i,e.seatAdjustment=0,e.submit=function(){var s={seatAdjustment:e.seatAdjustment};i||(s.seatAdjustment*=-1),e.submitPromise=r.organizations.putSeat({id:t.params.orgId},s).$promise.then(function(t){i?(o.eventTrack("Added Seats"),a.success("You have added "+e.seatAdjustment+" seats.")):(o.eventTrack("Removed Seats"),a.success("You have removed "+e.seatAdjustment+" seats.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingAdjustStorageController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,r,o,a,i){o.eventTrack("organizationBillingAdjustStorageController",{category:"Modal"}),e.add=i,e.storageAdjustment=0,e.submit=function(){var s={storageGbAdjustment:e.storageAdjustment};i||(s.storageGbAdjustment*=-1),e.submitPromise=r.organizations.putStorage({id:t.params.orgId},s).$promise.then(function(t){i?(o.eventTrack("Added Organization Storage"),a.success("You have added "+e.storageAdjustment+" GB.")):(o.eventTrack("Removed Organization Storage"),a.success("You have removed "+e.storageAdjustment+" GB.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingChangePaymentController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","existingPaymentMethod",function(e,t,n,r,o,a,i){o.eventTrack("organizationBillingChangePaymentController",{category:"Modal"}),e.existingPaymentMethod=i,e.paymentMethod="card",e.showPaymentOptions=!0,e.hidePaypal=!0,e.card={},e.bank={},e.changePaymentMethod=function(t){e.paymentMethod=t},e.submit=function(){var s=null;if("card"===e.paymentMethod)s=stripe.card.createToken(e.card);else{if("bank"!==e.paymentMethod)return;e.bank.currency="USD",e.bank.country="US",s=stripe.bankAccount.createToken(e.bank)}e.submitPromise=s.then(function(e){var n={paymentToken:e.id};return r.organizations.putPayment({id:t.params.orgId},n).$promise},function(e){throw e.message}).then(function(t){e.card=null,i?(o.eventTrack("Changed Organization Payment Method"),a.success("You have changed your payment method.")):(o.eventTrack("Added Organization Payment Method"),a.success("You have added a payment method.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingChangePlanController",["$scope","$state","apiService","$uibModalInstance","toastr","$analytics",function(e,t,n,r,o,a){a.eventTrack("organizationBillingChangePlanController",{category:"Modal"}),e.submit=function(){},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingController",["$scope","apiService","$state","$uibModal","toastr","$analytics","appSettings","tokenService","$window",function(e,t,n,r,o,a,i,s,l){e.selfHosted=i.selfHosted,e.charges=[],e.paymentSource=null,e.plan=null,e.subscription=null,e.loading=!0;function c(){t.organizations.getBilling({id:n.params.orgId},function(t){e.loading=!1,e.noSubscription=0===t.PlanType,e.canAdjustSeats=t.PlanType>1;var n=0;if(e.expiration=t.Expiration,t.License,e.plan={name:t.Plan,type:t.PlanType,seats:t.Seats},e.storage=null,e&&t.MaxStorageGb&&(e.storage={currentGb:t.StorageGb||0,maxGb:t.MaxStorageGb,currentName:t.StorageName||"0 GB"},e.storage.percentage=+(e.storage.currentGb/e.storage.maxGb*100).toFixed(2)),e.subscription=null,t.Subscription&&(e.subscription={trialEndDate:t.Subscription.TrialEndDate,cancelledDate:t.Subscription.CancelledDate,status:t.Subscription.Status,cancelled:t.Subscription.Cancelled,markedForCancel:!t.Subscription.Cancelled&&t.Subscription.CancelAtEndDate}),e.nextInvoice=null,t.UpcomingInvoice&&(e.nextInvoice={date:t.UpcomingInvoice.Date,amount:t.UpcomingInvoice.Amount}),t.Subscription&&t.Subscription.Items)for(e.subscription.items=[],n=0;n<t.Subscription.Items.length;n++)e.subscription.items.push({amount:t.Subscription.Items[n].Amount,name:t.Subscription.Items[n].Name,interval:t.Subscription.Items[n].Interval,qty:t.Subscription.Items[n].Quantity});e.paymentSource=null,t.PaymentSource&&(e.paymentSource={type:t.PaymentSource.Type,description:t.PaymentSource.Description,cardBrand:t.PaymentSource.CardBrand,needsVerification:t.PaymentSource.NeedsVerification});var r=[];for(n=0;n<t.Charges.length;n++)r.push({date:t.Charges[n].CreatedDate,paymentSource:t.Charges[n].PaymentSource?t.Charges[n].PaymentSource.Description:"-",amount:t.Charges[n].Amount,status:t.Charges[n].Status,failureMessage:t.Charges[n].FailureMessage,refunded:t.Charges[n].Refunded,partiallyRefunded:t.Charges[n].PartiallyRefunded,refundedAmount:t.Charges[n].RefundedAmount,invoiceId:t.Charges[n].InvoiceId});e.charges=r})}e.expiration=null,e.$on("$viewContentLoaded",function(){c()}),e.changePayment=function(){e.selfHosted||r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingChangePayment.html",controller:"organizationBillingChangePaymentController",resolve:{existingPaymentMethod:function(){return e.paymentSource?e.paymentSource.description:null}}}).result.then(function(){c()})},e.changePlan=function(){e.selfHosted||r.open({animation:!0,templateUrl:"app/organization/views/organizationBillingChangePlan.html",controller:"organizationBillingChangePlanController",resolve:{plan:function(){return e.plan}}}).result.then(function(){c()})},e.adjustSeats=function(t){!e.selfHosted&&e.canAdjustSeats&&r.open({animation:!0,templateUrl:"app/organization/views/organizationBillingAdjustSeats.html",controller:"organizationBillingAdjustSeatsController",resolve:{add:function(){return t}}}).result.then(function(){c()})},e.adjustStorage=function(t){e.selfHosted||r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingAdjustStorage.html",controller:"organizationBillingAdjustStorageController",resolve:{add:function(){return t}}}).result.then(function(){c()})},e.verifyBank=function(){e.selfHosted||r.open({animation:!0,templateUrl:"app/organization/views/organizationBillingVerifyBank.html",controller:"organizationBillingVerifyBankController"}).result.then(function(){c()})},e.cancel=function(){e.selfHosted||confirm("Are you sure you want to cancel? All users will lose access to the organization at the end of this billing cycle.")&&t.organizations.putCancel({id:n.params.orgId},{}).$promise.then(function(e){a.eventTrack("Canceled Plan"),o.success("Organization subscription has been canceled."),c()})},e.reinstate=function(){e.selfHosted||confirm("Are you sure you want to remove the cancellation request and reinstate this organization?")&&t.organizations.putReinstate({id:n.params.orgId},{}).$promise.then(function(e){a.eventTrack("Reinstated Plan"),o.success("Organization cancellation request has been removed."),c()})},e.updateLicense=function(){e.selfHosted&&r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingUpdateLicense.html",controller:"organizationBillingUpdateLicenseController"}).result.then(function(){c()})},e.license=function(){if(!e.selfHosted){var r=prompt("Enter your installation id");r&&""!==r&&t.organizations.getLicense({id:n.params.orgId,installationId:r},function(e){var t=JSON.stringify(e,null,2),n=new Blob([t]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(n,"bitwarden_organization_license.json");else{var r=window.document.createElement("a");r.href=window.URL.createObjectURL(n,{type:"text/plain"}),r.download="bitwarden_organization_license.json",document.body.appendChild(r),r.click(),document.body.removeChild(r)}},function(e){400===e.status?o.error("Invalid installation id."):o.error("Unable to generate license.")})}},e.viewInvoice=function(t){if(!e.selfHosted){var r=i.apiUri+"/organizations/"+n.params.orgId+"/billing-invoice/"+t.invoiceId+"?access_token="+s.getToken();l.open(r)}}}]),angular.module("bit.organization").controller("organizationBillingUpdateLicenseController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","validationService",function(e,t,n,r,o,a,i){o.eventTrack("organizationBillingUpdateLicenseController",{category:"Modal"}),e.submit=function(s){var l=document.getElementById("file").files;if(l&&l.length){var c=new FormData;c.append("license",l[0]),e.submitPromise=r.organizations.putLicense({id:t.params.orgId},c).$promise.then(function(e){o.eventTrack("Updated License"),a.success("You have updated your license."),n.close()})}else i.addError(s,"file","Select a license file.",!0)},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingVerifyBankController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr",function(e,t,n,r,o,a){o.eventTrack("organizationBillingVerifyBankController",{category:"Modal"}),e.submit=function(){var i={amount1:e.amount1,amount2:e.amount2};e.submitPromise=r.organizations.postVerifyBank({id:t.params.orgId},i).$promise.then(function(e){o.eventTrack("Verified Bank Account"),a.success("You have successfully verified your bank account."),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationCollectionsAddController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","authService",function(e,t,n,r,o,a,i){a.eventTrack("organizationCollectionsAddController",{category:"Modal"});var s=0;e.groups=[],e.selectedGroups={},e.loading=!0,e.useGroups=!1,n.opened.then(function(){return i.getUserProfile()}).then(function(n){if(n.organizations){var o=n.organizations[t.params.orgId];e.useGroups=!!o.useGroups}return e.useGroups?r.groups.listOrganization({orgId:t.params.orgId}).$promise:null}).then(function(t){if(t){for(var n=[],r=0;r<t.Data.length;r++)n.push({id:t.Data[r].Id,name:t.Data[r].Name,accessAll:t.Data[r].AccessAll}),t.Data[r].AccessAll||s++;e.groups=n,e.loading=!1}else e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.groups.length;r++)n[e.groups[r].id]={id:e.groups[r].id,readOnly:e.groups[r].id in e.selectedGroups&&e.selectedGroups[e.groups[r].id].readOnly};e.selectedGroups=n},e.toggleGroupSelection=function(t){t in e.selectedGroups?delete e.selectedGroups[t]:e.selectedGroups[t]={id:t,readOnly:!1}},e.toggleGroupReadOnlySelection=function(t){t.id in e.selectedGroups&&(e.selectedGroups[t.id].readOnly=!t.accessAll&&!e.selectedGroups[t.id].readOnly)},e.groupSelected=function(t){return t.id in e.selectedGroups||t.accessAll},e.allSelected=function(){return Object.keys(e.selectedGroups).length>=s},e.submit=function(i){var s=o.encryptCollection(i,t.params.orgId);if(e.useGroups)for(var l in s.groups=[],e.selectedGroups)if(e.selectedGroups.hasOwnProperty(l))for(var c=0;c<e.groups.length;c++)if(e.groups[c].id===e.selectedGroups[l].id){e.groups[c].accessAll||s.groups.push(e.selectedGroups[l]);break}e.submitPromise=r.collections.post({orgId:t.params.orgId},s,function(e){a.eventTrack("Created Collection");var r=o.decryptCollection(e,t.params.orgId,!0);n.close(r)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationCollectionsController",["$scope","$state","apiService","$uibModal","cipherService","$filter","toastr","$analytics","$uibModalStack",function(e,t,n,r,o,a,i,s,l){e.collections=[],e.loading=!0,e.$on("$viewContentLoaded",function(){n.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=o.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1,t.params.search&&(l.dismissAll(),e.filterSearch=t.params.search,$("#filterSearch").focus())})}),e.$on("organizationCollectionsAdd",function(t,n){e.add()}),e.add=function(){r.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsAdd.html",controller:"organizationCollectionsAddController"}).result.then(function(t){e.collections.push(t)})},e.edit=function(t){r.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsEdit.html",controller:"organizationCollectionsEditController",resolve:{id:function(){return t.id}}}).result.then(function(t){var n=a("filter")(e.collections,{id:t.id},!0);n&&n.length>0&&(n[0].name=t.name)})},e.users=function(e){r.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsUsers.html",controller:"organizationCollectionsUsersController",size:"lg",resolve:{collection:function(){return e}}}).result.then(function(){})},e.groups=function(e){r.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsGroups.html",controller:"organizationCollectionsGroupsController",resolve:{collection:function(){return e}}}).result.then(function(){})},e.delete=function(r){confirm("Are you sure you want to delete this collection ("+r.name+")?")&&n.collections.del({orgId:t.params.orgId,id:r.id},function(){var t=e.collections.indexOf(r);t>-1&&e.collections.splice(t,1),s.eventTrack("Deleted Collection"),i.success(r.name+" has been deleted.","Collection Deleted")},function(){i.error(r.name+" was not able to be deleted.","Error")})}}]),angular.module("bit.organization").controller("organizationCollectionsEditController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","id","authService",function(e,t,n,r,o,a,i,s){a.eventTrack("organizationCollectionsEditController",{category:"Modal"});var l=0;e.collection={},e.groups=[],e.selectedGroups={},e.loading=!0,e.useGroups=!1,n.opened.then(function(){return r.collections.getDetails({orgId:t.params.orgId,id:i}).$promise}).then(function(t){e.collection=o.decryptCollection(t);var n={};if(t.Groups)for(var r=0;r<t.Groups.length;r++)n[t.Groups[r].Id]={id:t.Groups[r].Id,readOnly:t.Groups[r].ReadOnly};return e.selectedGroups=n,s.getUserProfile()}).then(function(n){if(n.organizations){var o=n.organizations[t.params.orgId];e.useGroups=!!o.useGroups}return e.useGroups?r.groups.listOrganization({orgId:t.params.orgId}).$promise:null}).then(function(t){if(t){for(var n=[],r=0;r<t.Data.length;r++)n.push({id:t.Data[r].Id,name:t.Data[r].Name,accessAll:t.Data[r].AccessAll}),t.Data[r].AccessAll||l++;e.groups=n,e.loading=!1}else e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.groups.length;r++)n[e.groups[r].id]={id:e.groups[r].id,readOnly:e.groups[r].id in e.selectedGroups&&e.selectedGroups[e.groups[r].id].readOnly};e.selectedGroups=n},e.toggleGroupSelection=function(t){t in e.selectedGroups?delete e.selectedGroups[t]:e.selectedGroups[t]={id:t,readOnly:!1}},e.toggleGroupReadOnlySelection=function(t){t.id in e.selectedGroups&&(e.selectedGroups[t.id].readOnly=!t.accessAll&&!e.selectedGroups[t.id].readOnly)},e.groupSelected=function(t){return t.id in e.selectedGroups||t.accessAll},e.allSelected=function(){return Object.keys(e.selectedGroups).length>=l},e.submit=function(s){var l=o.encryptCollection(s,t.params.orgId);if(e.useGroups)for(var c in l.groups=[],e.selectedGroups)if(e.selectedGroups.hasOwnProperty(c))for(var u=0;u<e.groups.length;u++)if(e.groups[u].id===e.selectedGroups[c].id){e.groups[u].accessAll||l.groups.push(e.selectedGroups[c]);break}e.submitPromise=r.collections.put({orgId:t.params.orgId,id:i},l,function(e){a.eventTrack("Edited Collection");var r=o.decryptCollection(e,t.params.orgId,!0);n.close(r)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationCollectionsUsersController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","collection","toastr",function(e,t,n,r,o,a,i,s){a.eventTrack("organizationCollectionsUsersController",{category:"Modal"}),e.loading=!0,e.collection=i,e.users=[],n.opened.then(function(){e.loading=!1,r.collections.listUsers({orgId:t.params.orgId,id:i.id},function(t){if(t&&t.Data.length){for(var n=[],r=0;r<t.Data.length;r++)n.push({organizationUserId:t.Data[r].OrganizationUserId,name:t.Data[r].Name,email:t.Data[r].Email,type:t.Data[r].Type,status:t.Data[r].Status,readOnly:t.Data[r].ReadOnly,accessAll:t.Data[r].AccessAll});e.users=n}})}),e.remove=function(n){confirm("Are you sure you want to remove this user ("+n.email+") from this collection ("+i.name+")?")&&r.collections.delUser({orgId:t.params.orgId,id:i.id,orgUserId:n.organizationUserId},null,function(){s.success(n.email+" has been removed.","User Removed"),a.eventTrack("Removed User From Collection");var t=e.users.indexOf(n);t>-1&&e.users.splice(t,1)},function(){s.error("Unable to remove user.","Error")})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationDashboardController",["$scope","authService","$state","appSettings",function(e,t,n,r){e.selfHosted=r.selfHosted,e.$on("$viewContentLoaded",function(){t.getUserProfile().then(function(t){t.organizations&&(e.orgProfile=t.organizations[n.params.orgId])})}),e.goBilling=function(){n.go("backend.org.billing",{orgId:n.params.orgId})}}]),angular.module("bit.organization").controller("organizationDeleteController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics",function(e,t,n,r,o,a,i,s){s.eventTrack("organizationDeleteController",{category:"Modal"}),e.submit=function(){e.submitPromise=o.hashPassword(e.masterPassword).then(function(e){return n.organizations.del({id:t.params.orgId},{masterPasswordHash:e}).$promise}).then(function(){return r.dismiss("cancel"),a.removeProfileOrganization(t.params.orgId),s.eventTrack("Deleted Organization"),t.go("backend.user.vault")}).then(function(){i.success("This organization and all associated data has been deleted.","Organization Deleted")})},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationEventsController",["$scope","$state","apiService","$uibModal","$filter","toastr","$analytics","constants","eventService","$compile","$sce",function(e,t,n,r,o,a,i,s,l,c,u){e.events=[],e.orgUsers=[],e.loading=!0,e.continuationToken=null;var d=l.getDefaultDateFilters();e.filterStart=d.start,e.filterEnd=d.end,e.$on("$viewContentLoaded",function(){n.organizationUsers.list({orgId:t.params.orgId}).$promise.then(function(t){var n=[];for(p=0;p<t.Data.length;p++){var r={id:t.Data[p].Id,userId:t.Data[p].UserId,name:t.Data[p].Name,email:t.Data[p].Email};n.push(r);var o=r.name||r.email;m[r.userId]=o,g[r.id]=o}return e.orgUsers=n,f(!0)})}),e.refresh=function(){f(!0)},e.next=function(){f(!1)};var p=0,m={},g={};function f(r){var o=l.formatDateFilters(e.filterStart,e.filterEnd);if(!o.error)return r&&(e.continuationToken=null,e.events=[]),e.loading=!0,n.events.listOrganization({orgId:t.params.orgId,start:o.start,end:o.end,continuationToken:e.continuationToken}).$promise.then(function(t){e.continuationToken=t.ContinuationToken;var n=[];for(p=0;p<t.Data.length;p++){var r=t.Data[p].ActingUserId||t.Data[p].UserId,o=l.getEventInfo(t.Data[p]),a=c("<span>"+o.message+"</span>")(e);n.push({message:u.trustAsHtml(a[0].outerHTML),appIcon:o.appIcon,appName:o.appName,userId:r,userName:r&&m[r]||"-",date:t.Data[p].Date,ip:t.Data[p].IpAddress})}e.events&&e.events.length>0?e.events=e.events.concat(n):e.events=n,e.loading=!1});alert(o.error)}}]),angular.module("bit.organization").controller("organizationGroupsAddController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics",function(e,t,n,r,o,a){a.eventTrack("organizationGroupsAddController",{category:"Modal"}),e.collections=[],e.selectedCollections={},e.loading=!0,n.opened.then(function(){return r.collections.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){e.collections=o.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.collections.length;r++)n[e.collections[r].id]={id:e.collections[r].id,readOnly:e.collections[r].id in e.selectedCollections&&e.selectedCollections[e.collections[r].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(o){var i={name:o.name,accessAll:!!o.accessAll,externalId:o.externalId};if(!i.accessAll)for(var s in i.collections=[],e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&i.collections.push(e.selectedCollections[s]);e.submitPromise=r.groups.post({orgId:t.params.orgId},i,function(e){a.eventTrack("Created Group"),n.close({id:e.Id,name:e.Name})}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationGroupsController",["$scope","$state","apiService","$uibModal","$filter","toastr","$analytics","$uibModalStack",function(e,t,n,r,o,a,i,s){e.groups=[],e.loading=!0,e.$on("$viewContentLoaded",function(){n.groups.listOrganization({orgId:t.params.orgId},function(n){for(var r=[],o=0;o<n.Data.length;o++)r.push({id:n.Data[o].Id,name:n.Data[o].Name});e.groups=r,e.loading=!1,t.params.search&&(s.dismissAll(),e.filterSearch=t.params.search,$("#filterSearch").focus())})}),e.$on("organizationGroupsAdd",function(t,n){e.add()}),e.add=function(){r.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsAdd.html",controller:"organizationGroupsAddController"}).result.then(function(t){e.groups.push(t)})},e.edit=function(t){r.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsEdit.html",controller:"organizationGroupsEditController",resolve:{id:function(){return t.id}}}).result.then(function(t){var n=o("filter")(e.groups,{id:t.id},!0);n&&n.length>0&&(n[0].name=t.name)})},e.users=function(e){r.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsUsers.html",controller:"organizationGroupsUsersController",size:"lg",resolve:{group:function(){return e}}}).result.then(function(){})},e.delete=function(r){confirm("Are you sure you want to delete this group ("+r.name+")?")&&n.groups.del({orgId:t.params.orgId,id:r.id},function(){var t=e.groups.indexOf(r);t>-1&&e.groups.splice(t,1),i.eventTrack("Deleted Group"),a.success(r.name+" has been deleted.","Group Deleted")},function(){a.error(r.name+" was not able to be deleted.","Error")})}}]),angular.module("bit.organization").controller("organizationGroupsEditController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","id",function(e,t,n,r,o,a,i){a.eventTrack("organizationGroupsEditController",{category:"Modal"}),e.collections=[],e.selectedCollections={},e.loading=!0,n.opened.then(function(){return r.groups.getDetails({orgId:t.params.orgId,id:i}).$promise}).then(function(n){e.group={id:i,name:n.Name,externalId:n.ExternalId,accessAll:n.AccessAll};var o={};if(n.Collections)for(var a=0;a<n.Collections.length;a++)o[n.Collections[a].Id]={id:n.Collections[a].Id,readOnly:n.Collections[a].ReadOnly};return e.selectedCollections=o,r.collections.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){e.collections=o.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.collections.length;r++)n[e.collections[r].id]={id:e.collections[r].id,readOnly:e.collections[r].id in e.selectedCollections&&e.selectedCollections[e.collections[r].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(){var o={name:e.group.name,accessAll:!!e.group.accessAll,externalId:e.group.externalId};if(!o.accessAll)for(var s in o.collections=[],e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&o.collections.push(e.selectedCollections[s]);e.submitPromise=r.groups.put({orgId:t.params.orgId,id:i},o,function(e){a.eventTrack("Edited Group"),n.close({id:e.Id,name:e.Name})}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationGroupsUsersController",["$scope","$state","$uibModalInstance","apiService","$analytics","group","toastr",function(e,t,n,r,o,a,i){o.eventTrack("organizationGroupUsersController",{category:"Modal"}),e.loading=!0,e.group=a,e.users=[],n.opened.then(function(){return r.groups.listUsers({orgId:t.params.orgId,id:a.id}).$promise}).then(function(t){var n=[];if(t&&t.Data.length)for(var r=0;r<t.Data.length;r++)n.push({organizationUserId:t.Data[r].OrganizationUserId,name:t.Data[r].Name,email:t.Data[r].Email,type:t.Data[r].Type,status:t.Data[r].Status,accessAll:t.Data[r].AccessAll});e.users=n,e.loading=!1}),e.remove=function(n){confirm("Are you sure you want to remove this user ("+n.email+") from this group ("+a.name+")?")&&r.groups.delUser({orgId:t.params.orgId,id:a.id,orgUserId:n.organizationUserId},null,function(){i.success(n.email+" has been removed.","User Removed"),o.eventTrack("Removed User From Group");var t=e.users.indexOf(n);t>-1&&e.users.splice(t,1)},function(){i.error("Unable to remove user.","Error")})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleController",["$scope","$state","$uibModal","cryptoService","apiService","authService","toastr","$analytics","$filter","$uibModalStack",function(e,t,n,r,o,a,i,s,l,c){function u(){o.organizationUsers.list({orgId:t.params.orgId},function(n){for(var r=[],o=0;o<n.Data.length;o++){var a={id:n.Data[o].Id,userId:n.Data[o].UserId,name:n.Data[o].Name,email:n.Data[o].Email,status:n.Data[o].Status,type:n.Data[o].Type,accessAll:n.Data[o].AccessAll};r.push(a)}if(e.users=r,t.params.search&&(c.dismissAll(),e.filterSearch=t.params.search,$("#filterSearch").focus()),t.params.viewEvents){c.dismissAll();var i=l("filter")(e.users,{id:t.params.viewEvents});i&&i.length&&e.events(i[0])}})}e.users=[],e.useGroups=!1,e.useEvents=!1,e.$on("$viewContentLoaded",function(){u(),a.getUserProfile().then(function(n){if(n.organizations){var r=n.organizations[t.params.orgId];e.useGroups=!!r.useGroups,e.useEvents=!!r.useEvents}})}),e.reinvite=function(e){o.organizationUsers.reinvite({orgId:t.params.orgId,id:e.id},null,function(){s.eventTrack("Reinvited User"),i.success(e.email+" has been invited again.","User Invited")},function(){i.error("Unable to invite user.","Error")})},e.delete=function(n){confirm("Are you sure you want to remove this user ("+n.email+")?")&&o.organizationUsers.del({orgId:t.params.orgId,id:n.id},null,function(){s.eventTrack("Deleted User"),i.success(n.email+" has been removed.","User Removed");var t=e.users.indexOf(n);t>-1&&e.users.splice(t,1)},function(){i.error("Unable to remove user.","Error")})},e.confirm=function(e){o.users.getPublicKey({id:e.userId},function(n){var a=r.getOrgKey(t.params.orgId);if(a){var l=r.rsaEncrypt(a.key,n.PublicKey);o.organizationUsers.confirm({orgId:t.params.orgId,id:e.id},{key:l},function(){e.status=2,s.eventTrack("Confirmed User"),i.success(e.email+" has been confirmed.","User Confirmed")},function(){i.error("Unable to confirm user.","Error")})}else i.error("Unable to confirm user.","Error")},function(){i.error("Unable to confirm user.","Error")})},e.$on("organizationPeopleInvite",function(t,n){e.invite()}),e.invite=function(){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleInvite.html",controller:"organizationPeopleInviteController"}).result.then(function(){u()})},e.edit=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleEdit.html",controller:"organizationPeopleEditController",resolve:{orgUser:function(){return e}}}).result.then(function(){u()})},e.groups=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleGroups.html",controller:"organizationPeopleGroupsController",resolve:{orgUser:function(){return e}}}).result.then(function(){})},e.events=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleEvents.html",controller:"organizationPeopleEventsController",resolve:{orgUser:function(){return e},orgId:function(){return t.params.orgId}}})}}]),angular.module("bit.organization").controller("organizationPeopleEditController",["$scope","$state","$uibModalInstance","apiService","cipherService","orgUser","$analytics",function(e,t,n,r,o,a,i){i.eventTrack("organizationPeopleEditController",{category:"Modal"}),e.loading=!0,e.collections=[],e.selectedCollections={},n.opened.then(function(){r.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=o.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),r.organizationUsers.get({orgId:t.params.orgId,id:a.id},function(t){var n={};if(t&&t.Collections)for(var r=0;r<t.Collections.length;r++)n[t.Collections[r].Id]={id:t.Collections[r].Id,readOnly:t.Collections[r].ReadOnly};e.email=a.email,e.type=t.Type,e.accessAll=t.AccessAll,e.selectedCollections=n})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.collections.length;r++)n[e.collections[r].id]={id:e.collections[r].id,readOnly:e.collections[r].id in e.selectedCollections&&e.selectedCollections[e.collections[r].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submitPromise=null,e.submit=function(o){var s=[];if(!e.accessAll)for(var l in e.selectedCollections)e.selectedCollections.hasOwnProperty(l)&&s.push(e.selectedCollections[l]);e.submitPromise=r.organizationUsers.put({orgId:t.params.orgId,id:a.id},{type:e.type,collections:s,accessAll:e.accessAll},function(){i.eventTrack("Edited User"),n.close()}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleEventsController",["$scope","apiService","$uibModalInstance","orgUser","$analytics","eventService","orgId","$compile","$sce",function(e,t,n,r,o,a,i,s,l){o.eventTrack("organizationPeopleEventsController",{category:"Modal"}),e.email=r.email,e.events=[],e.loading=!0,e.continuationToken=null;var c=a.getDefaultDateFilters();function u(n){var o=a.formatDateFilters(e.filterStart,e.filterEnd);if(!o.error)return n&&(e.continuationToken=null,e.events=[]),e.loading=!0,t.events.listOrganizationUser({orgId:i,id:r.id,start:o.start,end:o.end,continuationToken:e.continuationToken}).$promise.then(function(t){e.continuationToken=t.ContinuationToken;for(var n=[],r=0;r<t.Data.length;r++){var o=a.getEventInfo(t.Data[r]),i=s("<span>"+o.message+"</span>")(e);n.push({message:l.trustAsHtml(i[0].outerHTML),appIcon:o.appIcon,appName:o.appName,date:t.Data[r].Date,ip:t.Data[r].IpAddress})}e.events&&e.events.length>0?e.events=e.events.concat(n):e.events=n,e.loading=!1});alert(o.error)}e.filterStart=c.start,e.filterEnd=c.end,n.opened.then(function(){u(!0)}),e.refresh=function(){u(!0)},e.next=function(){u(!1)},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleGroupsController",["$scope","$state","$uibModalInstance","apiService","orgUser","$analytics",function(e,t,n,r,o,a){a.eventTrack("organizationPeopleGroupsController",{category:"Modal"}),e.loading=!0,e.groups=[],e.selectedGroups={},e.orgUser=o,n.opened.then(function(){return r.groups.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){for(var a=[],i=0;i<n.Data.length;i++)a.push({id:n.Data[i].Id,name:n.Data[i].Name});return e.groups=a,r.organizationUsers.listGroups({orgId:t.params.orgId,id:o.id}).$promise}).then(function(t){var n={};if(t)for(var r=0;r<t.length;r++)n[t[r]]=!0;e.selectedGroups=n,e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.groups.length;r++)n[e.groups[r].id]=!0;e.selectedGroups=n},e.toggleGroupSelection=function(t){t in e.selectedGroups?delete e.selectedGroups[t]:e.selectedGroups[t]=!0},e.groupSelected=function(t){return t.id in e.selectedGroups},e.allSelected=function(){return Object.keys(e.selectedGroups).length===e.groups.length},e.submitPromise=null,e.submit=function(i){var s=[];for(var l in e.selectedGroups)e.selectedGroups.hasOwnProperty(l)&&s.push(l);e.submitPromise=r.organizationUsers.putGroups({orgId:t.params.orgId,id:o.id},{groupIds:s},function(){a.eventTrack("Edited User Groups"),n.close()}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationPeopleInviteController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics",function(e,t,n,r,o,a){a.eventTrack("organizationPeopleInviteController",{category:"Modal"}),e.loading=!0,e.collections=[],e.selectedCollections={},e.model={type:"User"},n.opened.then(function(){r.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=o.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.collections.length;r++)n[e.collections[r].id]={id:e.collections[r].id,readOnly:e.collections[r].id in e.selectedCollections&&e.selectedCollections[e.collections[r].id].readOnly};e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]={id:t,readOnly:!1}},e.toggleCollectionReadOnlySelection=function(t){t in e.selectedCollections&&(e.selectedCollections[t].readOnly=!e.selectedCollections[t].readOnly)},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submitPromise=null,e.submit=function(o){var i=[];if(!o.accessAll)for(var s in e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&i.push(e.selectedCollections[s]);var l=o.emails.trim().split(/\s*,\s*/);e.submitPromise=r.organizationUsers.invite({orgId:t.params.orgId},{emails:l,type:o.type,collections:i,accessAll:o.accessAll},function(){a.eventTrack("Invited User"),n.close()}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationSettingsController",["$scope","$state","apiService","toastr","authService","$uibModal","$analytics","appSettings",function(e,t,n,r,o,a,i,s){e.selfHosted=s.selfHosted,e.model={},e.$on("$viewContentLoaded",function(){n.organizations.get({id:t.params.orgId},function(t){e.model={name:t.Name,billingEmail:t.BillingEmail,businessName:t.BusinessName,businessAddress1:t.BusinessAddress1,businessAddress2:t.BusinessAddress2,businessAddress3:t.BusinessAddress3,businessCountry:t.BusinessCountry,businessTaxNumber:t.BusinessTaxNumber}})}),e.generalSave=function(){e.selfHosted||(e.generalPromise=n.organizations.put({id:t.params.orgId},e.model,function(e){o.updateProfileOrganization(e).then(function(e){i.eventTrack("Updated Organization Settings"),r.success("Organization has been updated.","Success!")})}).$promise)},e.import=function(){a.open({animation:!0,templateUrl:"app/tools/views/toolsImport.html",controller:"organizationSettingsImportController"})},e.export=function(){a.open({animation:!0,templateUrl:"app/tools/views/toolsExport.html",controller:"organizationSettingsExportController"})},e.delete=function(){a.open({animation:!0,templateUrl:"app/organization/views/organizationDelete.html",controller:"organizationDeleteController"})}}]),angular.module("bit.organization").controller("organizationSettingsExportController",["$scope","apiService","$uibModalInstance","cipherService","$q","toastr","$analytics","$state","constants",function(e,t,n,r,o,a,i,s,l){function c(){var e=new Date;return"bitwarden_org_export_"+(e.getFullYear()+""+u(e.getMonth()+1,2)+u(e.getDate(),2)+u(e.getHours(),2)+u(e.getMinutes(),2)+u(e.getSeconds(),2))+".csv"}function u(e,t,n){return n=n||"0",(e+="").length>=t?e:new Array(t-e.length+1).join(n)+e}i.eventTrack("organizationSettingsExportController",{category:"Modal"}),e.export=function(n){e.startedExport=!0;var u=[],d=[],p=t.collections.listOrganization({orgId:s.params.orgId},function(e){d=r.decryptCollections(e.Data,s.params.orgId,!0)}).$promise,m=t.ciphers.listOrganizationDetails({organizationId:s.params.orgId},function(e){u=r.decryptCiphers(e.Data)}).$promise;o.all([p,m]).then(function(){if(!u.length)return a.error("Nothing to export.","Error!"),void e.close();var t,n={};for(t=0;t<d.length;t++)n[d[t].id]=d[t];try{var r=[];for(t=0;t<u.length;t++)if(u[t].type===l.cipherType.login||u[t].type===l.cipherType.secureNote){var o,s={collections:[],type:null,name:u[t].name,notes:u[t].notes,fields:null,login_uri:null,login_username:null,login_password:null,login_totp:null};if(u[t].collectionIds)for(o=0;o<u[t].collectionIds.length;o++)n.hasOwnProperty(u[t].collectionIds[o])&&s.collections.push(n[u[t].collectionIds[o]].name);if(u[t].fields)for(o=0;o<u[t].fields.length;o++)s.fields?s.fields+="\n":s.fields="",s.fields+=(u[t].fields[o].name||"")+": "+u[t].fields[o].value;switch(u[t].type){case l.cipherType.login:if(s.type="login",s.login_uri=null,s.login_username=u[t].login.username,s.login_password=u[t].login.password,s.login_totp=u[t].login.totp,u[t].login.uris&&u[t].login.uris.length)for(s.login_uri=[],o=0;o<u[t].login.uris.length;o++)s.login_uri.push(u[t].login.uris[o].uri);break;case l.cipherType.secureNote:s.type="note";break;default:continue}r.push(s)}var p=Papa.unparse(r),m=new Blob([p]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(m,c());else{var g=window.document.createElement("a");g.href=window.URL.createObjectURL(m,{type:"text/plain"}),g.download=c(),document.body.appendChild(g),g.click(),document.body.removeChild(g)}i.eventTrack("Exported Organization Data"),a.success("Your data has been exported. Check your browser's downloads folder.","Success!"),e.close()}catch(t){a.error("Something went wrong. Please try again.","Error!"),e.close()}},function(){a.error("Something went wrong. Please try again.","Error!"),e.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationSettingsImportController",["$scope","$state","apiService","$uibModalInstance","cipherService","toastr","importService","$analytics","$sce","validationService","cryptoService",function(e,t,n,r,o,a,i,s,l,c,u){function d(i,l,c){if(i.length||l.length){if(l.length){var d=Math.floor(l.length/2),g=l.length-1;if(p(l[0])&&p(l[d])&&p(l[g]))return void m("Data is not formatted correctly. Please check your import file and try again.")}n.ciphers.importOrg({orgId:t.params.orgId},{collections:o.encryptCollections(i,t.params.orgId),ciphers:o.encryptCiphers(l,u.getOrgKey(t.params.orgId)),collectionRelationships:c},function(){r.dismiss("cancel"),t.go("backend.org.vault",{orgId:t.params.orgId}).then(function(){s.eventTrack("Imported Org Data",{label:e.model.source}),a.success("Data has been successfully imported into your vault.","Import Success")})},m)}else m("Nothing was imported.")}function p(e){return(null===e.name||"--"===e.name)&&e.login&&(null===e.login.password||""===e.login.password)}function m(t){if(s.eventTrack("Import Org Data Failed",{label:e.model.source}),r.dismiss("cancel"),t){var n=t.data;if(!n||!n.ValidationErrors)return n&&n.Message?void a.error(n.Message):void a.error(t);var o="";for(var i in n.ValidationErrors)if(n.ValidationErrors.hasOwnProperty(i))for(var l=0;l<n.ValidationErrors[i].length;l++)o+=i+": "+n.ValidationErrors[i][l]+" ";if(""!==o)return void a.error(o)}a.error("Something went wrong. Try again.","Oh No!")}s.eventTrack("organizationSettingsImportController",{category:"Modal"}),e.model={source:""},e.source={},e.splitFeatured=!1,e.options=[{id:"bitwardencsv",name:"Bitwarden (csv)",featured:!0,sort:1,instructions:l.trustAsHtml('Export using the web vault (vault.bitwarden.com). Log into the web vault and navigate to your organization\'s admin area. Then to go "Settings" > "Tools" > "Export".')},{id:"lastpass",name:"LastPass (csv)",featured:!0,sort:2,instructions:l.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-lastpass/">https://help.bitwarden.com/article/import-from-lastpass/</a>')}],e.setSource=function(){for(var t=0;t<e.options.length;t++)if(e.options[t].id===e.model.source){e.source=e.options[t];break}},e.setSource(),e.import=function(t,n){if(t.source&&""!==t.source){var r=document.getElementById("file").files[0];r||t.fileContents&&""!==t.fileContents?(e.processing=!0,i.importOrg(t.source,r||t.fileContents,d,m)):c.addError(n,"file","Select the import file or copy/paste the import file contents.",!0)}else c.addError(n,"source","Select the format of the import file.",!0)},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationVaultAddCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","$analytics","authService","orgId","$uibModal","constants","selectedType",function(e,t,n,r,o,a,i,s,l,c,u,d){function p(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}i.eventTrack("organizationVaultAddCipherController",{category:"Modal"}),e.constants=u,e.selectedType=d?d.toString():u.cipherType.login.toString(),e.cipher={type:d||u.cipherType.login,login:{uris:[{uri:null,match:null,matchValue:null}]},identity:{},card:{},secureNote:{type:"0"}},e.hideFolders=e.hideFavorite=e.fromOrg=!0,s.getUserProfile().then(function(t){var n=t.organizations[l];e.useTotp=n.useTotp}),e.typeChanged=function(){e.cipher.type=parseInt(e.selectedType)},e.savePromise=null,e.save=function(){e.cipher.organizationId=l;var r=o.encryptCipher(e.cipher);e.savePromise=t.ciphers.postAdmin(r,function(e){i.eventTrack("Created Organization Cipher");var t=o.decryptCipherPreview(e);n.close(t)}).$promise},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(i.eventTrack("Generated Password From Add"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addUri=function(){e.cipher.login&&(e.cipher.login.uris||(e.cipher.login.uris=[]),e.cipher.login.uris.push({uri:null,match:null,matchValue:null}))},e.removeUri=function(t){if(e.cipher.login&&e.cipher.login.uris){var n=e.cipher.login.uris.indexOf(t);n>-1&&e.cipher.login.uris.splice(n,1)}},e.uriMatchChanged=function(e){!e.matchValue&&0!==e.matchValue||""===e.matchValue?e.match=null:e.match=parseInt(e.matchValue)},e.addField=function(){e.cipher.fields||(e.cipher.fields=[]),e.cipher.fields.push({type:u.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.clipboardSuccess=function(e){e.clearSelection(),p(e)},e.clipboardError=function(e,t){t&&p(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.close=function(){n.dismiss("close")},e.showUpgrade=function(){c.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return l}}})}}]),angular.module("bit.organization").controller("organizationVaultAttachmentsController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","cipherId","$analytics","validationService","toastr","$timeout",function(e,t,n,r,o,a,i,s,l,c){i.eventTrack("organizationVaultAttachmentsController",{category:"Modal"}),e.cipher={},e.loading=!0,e.isPremium=!0,e.canUseAttachments=!0;var u=!1;t.ciphers.getAdmin({id:a},function(t){e.cipher=o.decryptCipher(t),e.loading=!1},function(){e.loading=!1}),e.save=function(c){var d=document.getElementById("file").files;if(d&&d.length){var p=r.getOrgKey(e.cipher.organizationId);e.savePromise=o.encryptAttachmentFile(p,d[0]).then(function(e){var n=new FormData,r=new Blob([e.data],{type:"application/octet-stream"});return n.append("data",r,e.fileName),t.ciphers.postAttachmentAdmin({id:a},n).$promise}).then(function(e){i.eventTrack("Added Attachment"),l.success("The attachment has been added."),u=!0,n.close(!0)},function(e){var t=s.parseErrors(e);l.error(t.length?t[0]:"An error occurred.")})}else s.addError(c,"file","Select a file.",!0)},e.download=function(t){t.loading=!0;var n=r.getOrgKey(e.cipher.organizationId);o.downloadAndDecryptAttachment(n,t,!0).then(function(e){c(function(){t.loading=!1})},function(){c(function(){t.loading=!1})})},e.remove=function(n){confirm("Are you sure you want to delete this attachment ("+n.fileName+")?")&&(n.loading=!0,t.ciphers.delAttachmentAdmin({id:a,attachmentId:n.id}).$promise.then(function(){n.loading=!1,i.eventTrack("Deleted Organization Attachment");var t=e.cipher.attachments.indexOf(n);t>-1&&e.cipher.attachments.splice(t,1)},function(){l.error("Cannot delete attachment."),n.loading=!1}))},e.close=function(){n.dismiss("cancel")},e.$on("modal.closing",function(t,r,o){u||(t.preventDefault(),u=!0,n.close(!!e.cipher.attachments&&e.cipher.attachments.length>0))})}]),angular.module("bit.organization").controller("organizationVaultCipherCollectionsController",["$scope","apiService","$uibModalInstance","cipherService","cipher","$analytics","collections",function(e,t,n,r,o,a,i){a.eventTrack("organizationVaultCipherCollectionsController",{category:"Modal"}),e.cipher={},e.collections=[],e.selectedCollections={},n.opened.then(function(){for(var t=[],n=0;n<i.length;n++)i[n].id&&t.push(i[n]);e.collections=t,e.cipher=o;var r={};if(e.cipher.collectionIds)for(n=0;n<e.cipher.collectionIds.length;n++)r[e.cipher.collectionIds[n]]=!0;e.selectedCollections=r}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.collections.length;r++)n[e.collections[r].id]=!0;e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]=!0},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(){var r={collectionIds:[]};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&r.collectionIds.push(i);e.submitPromise=t.ciphers.putCollectionsAdmin({id:o.id},r).$promise.then(function(e){a.eventTrack("Edited Cipher Collections"),n.close({action:"collectionsEdit",collectionIds:r.collectionIds})})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationVaultCipherEventsController",["$scope","apiService","$uibModalInstance","cipher","$analytics","eventService",function(e,t,n,r,o,a){o.eventTrack("organizationVaultCipherEventsController",{category:"Modal"}),e.cipher=r,e.events=[],e.loading=!0,e.continuationToken=null;var i=a.getDefaultDateFilters();e.filterStart=i.start,e.filterEnd=i.end,n.opened.then(function(){t.organizationUsers.list({orgId:r.organizationId}).$promise.then(function(t){var n=[];for(s=0;s<t.Data.length;s++){var r={id:t.Data[s].Id,userId:t.Data[s].UserId,name:t.Data[s].Name,email:t.Data[s].Email};n.push(r);var o=r.name||r.email;l[r.userId]=o,c[r.id]=o}return e.orgUsers=n,u(!0)})}),e.refresh=function(){u(!0)},e.next=function(){u(!1)};var s=0,l={},c={};function u(n){var o=a.formatDateFilters(e.filterStart,e.filterEnd);if(!o.error)return n&&(e.continuationToken=null,e.events=[]),e.loading=!0,t.events.listCipher({id:r.id,start:o.start,end:o.end,continuationToken:e.continuationToken}).$promise.then(function(t){e.continuationToken=t.ContinuationToken;var n=[];for(s=0;s<t.Data.length;s++){var r=t.Data[s].ActingUserId||t.Data[s].UserId,o=a.getEventInfo(t.Data[s],{cipherInfo:!1});n.push({message:o.message,appIcon:o.appIcon,appName:o.appName,userId:r,userName:r&&l[r]||"-",date:t.Data[s].Date,ip:t.Data[s].IpAddress})}e.events&&e.events.length>0?e.events=e.events.concat(n):e.events=n,e.loading=!1});alert(o.error)}e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationVaultController",["$scope","apiService","cipherService","$analytics","$q","$state","$localStorage","$uibModal","$filter","authService","$uibModalStack","constants","$timeout",function(e,t,n,r,o,a,i,s,l,c,u,d,p){function m(){e.selectedCollection=void 0,e.selectedType=void 0,e.selectedAll=!1}function g(){$.AdminLTE&&$.AdminLTE.layout&&p(function(){$.AdminLTE.layout.fix()},0)}e.ciphers=[],e.collections=[],e.loading=!0,e.useEvents=!1,e.constants=d,e.filter=void 0,e.selectedType=void 0,e.selectedCollection=void 0,e.selectedAll=!0,e.selectedTitle="All",e.selectedIcon="fa-th",e.$on("$viewContentLoaded",function(){c.getUserProfile().then(function(t){if(t.organizations){var n=t.organizations[a.params.orgId];e.useEvents=!!n.useEvents}});var r=t.collections.listOrganization({orgId:a.params.orgId},function(t){for(var r=[{id:null,name:"Unassigned"}],o=0;o<t.Data.length;o++){var a=n.decryptCollection(t.Data[o],null,!0);r.push(a)}e.collections=r}).$promise,i=t.ciphers.listOrganizationDetails({organizationId:a.params.orgId},function(t){for(var r=[],o=0;o<t.Data.length;o++){var a=n.decryptCipherPreview(t.Data[o]);r.push(a)}e.ciphers=r}).$promise;o.all([r,i]).then(function(){if(e.loading=!1,p(function(){$("body").hasClass("control-sidebar-open")&&$("#search").focus()},500),a.params.search&&(u.dismissAll(),e.searchVaultText=a.params.search),a.params.viewEvents){u.dismissAll();var t=l("filter")(e.ciphers,{id:a.params.viewEvents});t&&t.length&&e.viewEvents(t[0])}})}),e.collectionSort=function(e){return e.id?e.name.toLowerCase():""},e.editCipher=function(t){s.open({animation:!0,templateUrl:"app/vault/views/vaultEditCipher.html",controller:"organizationVaultEditCipherController",resolve:{cipherId:function(){return t.id},orgId:function(){return a.params.orgId}}}).result.then(function(n){var r;"edit"===n.action?(r=e.ciphers.indexOf(t))>-1&&(n.data.collectionIds=e.ciphers[r].collectionIds,e.ciphers[r]=n.data):"delete"===n.action&&(r=e.ciphers.indexOf(t))>-1&&e.ciphers.splice(r,1)})},e.$on("organizationVaultAddCipher",function(t,n){e.addCipher()}),e.addCipher=function(){s.open({animation:!0,templateUrl:"app/vault/views/vaultAddCipher.html",controller:"organizationVaultAddCipherController",resolve:{orgId:function(){return a.params.orgId},selectedType:function(){return e.selectedType}}}).result.then(function(t){e.ciphers.push(t)})},e.editCollections=function(t){s.open({animation:!0,templateUrl:"app/organization/views/organizationVaultCipherCollections.html",controller:"organizationVaultCipherCollectionsController",resolve:{cipher:function(){return t},collections:function(){return e.collections}}}).result.then(function(e){e.collectionIds&&(t.collectionIds=e.collectionIds)})},e.viewEvents=function(e){s.open({animation:!0,templateUrl:"app/organization/views/organizationVaultCipherEvents.html",controller:"organizationVaultCipherEventsController",resolve:{cipher:function(){return e}}})},e.attachments=function(e){c.getUserProfile().then(function(t){return!!t.organizations[e.organizationId].maxStorageGb}).then(function(t){t?s.open({animation:!0,templateUrl:"app/vault/views/vaultAttachments.html",controller:"organizationVaultAttachmentsController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){e.hasAttachments=t}):s.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return e.organizationId}}})})},e.deleteCipher=function(n){confirm("Are you sure you want to delete this item ("+n.name+")?")&&t.ciphers.delAdmin({id:n.id},function(){r.eventTrack("Deleted Cipher");var t=e.ciphers.indexOf(n);t>-1&&e.ciphers.splice(t,1)})},e.filterCollection=function(t){m(),e.selectedCollection=t,e.selectedIcon="fa-cube",e.filter=function(e){return e.collectionIds&&e.collectionIds.indexOf(t.id)>-1},g()},e.filterType=function(t){switch(m(),e.selectedType=t,t){case d.cipherType.login:e.selectedTitle="Login",e.selectedIcon="fa-globe";break;case d.cipherType.card:e.selectedTitle="Card",e.selectedIcon="fa-credit-card";break;case d.cipherType.identity:e.selectedTitle="Identity",e.selectedIcon="fa-id-card-o";break;case d.cipherType.secureNote:e.selectedTitle="Secure Note",e.selectedIcon="fa-sticky-note-o"}e.filter=function(e){return e.type===t},g()},e.filterAll=function(){m(),e.selectedAll=!0,e.selectedTitle="All",e.selectedIcon="fa-th",e.filter=null,g()},e.cipherFilter=function(){return function(t){return!e.filter||e.filter(t)}}}]),angular.module("bit.organization").controller("organizationVaultEditCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","cipherId","$analytics","orgId","$uibModal","constants",function(e,t,n,r,o,a,i,s,l,c,u){function d(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("organizationVaultEditCipherController",{category:"Modal"}),e.cipher={},e.hideFolders=e.hideFavorite=e.fromOrg=!0,e.constants=u,t.ciphers.getAdmin({id:i},function(t){e.cipher=o.decryptCipher(t),e.useTotp=e.cipher.organizationUseTotp,function(){if(e.cipher.login&&e.cipher.login.uris)for(var t=0;t<e.cipher.login.uris.length;t++)e.cipher.login.uris[t].matchValue=e.cipher.login.uris[t].match||0===e.cipher.login.uris[t].match?e.cipher.login.uris[t].match.toString():""}()}),e.save=function(r){var a=o.encryptCipher(r,e.cipher.type);e.savePromise=t.ciphers.putAdmin({id:i},a,function(e){s.eventTrack("Edited Organization Cipher");var t=o.decryptCipherPreview(e);n.close({action:"edit",data:t})}).$promise},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Edit"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addUri=function(){e.cipher.login&&(e.cipher.login.uris||(e.cipher.login.uris=[]),e.cipher.login.uris.push({uri:null,match:null,matchValue:null}))},e.removeUri=function(t){if(e.cipher.login&&e.cipher.login.uris){var n=e.cipher.login.uris.indexOf(t);n>-1&&e.cipher.login.uris.splice(n,1)}},e.uriMatchChanged=function(e){!e.matchValue&&0!==e.matchValue||""===e.matchValue?e.match=null:e.match=parseInt(e.matchValue)},e.addField=function(){e.cipher.login.fields||(e.cipher.login.fields=[]),e.cipher.fields.push({type:u.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.clipboardSuccess=function(e){e.clearSelection(),d(e)},e.clipboardError=function(e,t){t&&d(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.delete=function(){confirm("Are you sure you want to delete this item ("+e.cipher.name+")?")&&t.ciphers.delAdmin({id:e.cipher.id},function(){s.eventTrack("Deleted Organization Cipher From Edit"),n.close({action:"delete",data:e.cipher.id})})},e.close=function(){n.dismiss("cancel")},e.showUpgrade=function(){c.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return l}}})}}]),angular.module("bit.tools").controller("reportsBreachController",["$scope","apiService","toastr","authService",function(e,t,n,r){e.loading=!0,e.error=!1,e.breachAccounts=[],e.email=null,e.$on("$viewContentLoaded",function(){r.getUserProfile().then(function(n){return e.email=n.email,t.hibp.get({email:e.email}).$promise}).then(function(t){for(var n=[],r=0;r<t.length;r++){var o={id:t[r].Name,title:t[r].Title,domain:t[r].Domain,date:new Date(t[r].BreachDate),reportedDate:new Date(t[r].AddedDate),modifiedDate:new Date(t[r].ModifiedDate),count:t[r].PwnCount,description:t[r].Description,classes:t[r].DataClasses,image:"https://haveibeenpwned.com/Content/Images/PwnedLogos/"+t[r].Name+"."+t[r].LogoType};n.push(o)}e.breachAccounts=n,e.loading=!1},function(t){e.error=404!==t.status,e.loading=!1})})}]),angular.module("bit.services").factory("apiService",["$resource","tokenService","appSettings","$httpParamSerializer","utilsService",function(e,t,n,r,o){var a={},i=n.apiUri,s=n.identityUri;return a.folders=e(i+"/folders/:id",{},{get:{method:"GET",params:{id:"@id"}},list:{method:"GET",params:{}},post:{method:"POST",params:{}},put:{method:"POST",params:{id:"@id"}},del:{url:i+"/folders/:id/delete",method:"POST",params:{id:"@id"}}}),a.ciphers=e(i+"/ciphers/:id",{},{get:{method:"GET",params:{id:"@id"}},getAdmin:{url:i+"/ciphers/:id/admin",method:"GET",params:{id:"@id"}},getDetails:{url:i+"/ciphers/:id/details",method:"GET",params:{id:"@id"}},list:{method:"GET",params:{}},listDetails:{url:i+"/ciphers/details",method:"GET",params:{}},listOrganizationDetails:{url:i+"/ciphers/organization-details",method:"GET",params:{}},post:{method:"POST",params:{}},postAdmin:{url:i+"/ciphers/admin",method:"POST",params:{}},put:{method:"POST",params:{id:"@id"}},putAdmin:{url:i+"/ciphers/:id/admin",method:"POST",params:{id:"@id"}},import:{url:i+"/ciphers/import",method:"POST",params:{}},importOrg:{url:i+"/ciphers/import-organization?organizationId=:orgId",method:"POST",params:{orgId:"@orgId"}},putPartial:{url:i+"/ciphers/:id/partial",method:"POST",params:{id:"@id"}},putShare:{url:i+"/ciphers/:id/share",method:"POST",params:{id:"@id"}},putCollections:{url:i+"/ciphers/:id/collections",method:"POST",params:{id:"@id"}},putCollectionsAdmin:{url:i+"/ciphers/:id/collections-admin",method:"POST",params:{id:"@id"}},del:{url:i+"/ciphers/:id/delete",method:"POST",params:{id:"@id"}},delAdmin:{url:i+"/ciphers/:id/delete-admin",method:"POST",params:{id:"@id"}},delMany:{url:i+"/ciphers/delete",method:"POST"},moveMany:{url:i+"/ciphers/move",method:"POST"},purge:{url:i+"/ciphers/purge",method:"POST"},postAttachment:{url:i+"/ciphers/:id/attachment",method:"POST",headers:{"Content-Type":void 0},params:{id:"@id"}},postAttachmentAdmin:{url:i+"/ciphers/:id/attachment-admin",method:"POST",headers:{"Content-Type":void 0},params:{id:"@id"}},postShareAttachment:{url:i+"/ciphers/:id/attachment/:attachmentId/share?organizationId=:orgId",method:"POST",headers:{"Content-Type":void 0},params:{id:"@id",attachmentId:"@attachmentId",orgId:"@orgId"}},delAttachment:{url:i+"/ciphers/:id/attachment/:attachmentId/delete",method:"POST",params:{id:"@id",attachmentId:"@attachmentId"}},delAttachmentAdmin:{url:i+"/ciphers/:id/attachment/:attachmentId/delete-admin",method:"POST",params:{id:"@id",attachmentId:"@attachmentId"}}}),a.organizations=e(i+"/organizations/:id",{},{get:{method:"GET",params:{id:"@id"}},getBilling:{url:i+"/organizations/:id/billing",method:"GET",params:{id:"@id"}},getLicense:{url:i+"/organizations/:id/license",method:"GET",params:{id:"@id"}},list:{method:"GET",params:{}},post:{method:"POST",params:{}},put:{method:"POST",params:{id:"@id"}},putPayment:{url:i+"/organizations/:id/payment",method:"POST",params:{id:"@id"}},putSeat:{url:i+"/organizations/:id/seat",method:"POST",params:{id:"@id"}},putStorage:{url:i+"/organizations/:id/storage",method:"POST",params:{id:"@id"}},putUpgrade:{url:i+"/organizations/:id/upgrade",method:"POST",params:{id:"@id"}},putCancel:{url:i+"/organizations/:id/cancel",method:"POST",params:{id:"@id"}},putReinstate:{url:i+"/organizations/:id/reinstate",method:"POST",params:{id:"@id"}},postLeave:{url:i+"/organizations/:id/leave",method:"POST",params:{id:"@id"}},postVerifyBank:{url:i+"/organizations/:id/verify-bank",method:"POST",params:{id:"@id"}},del:{url:i+"/organizations/:id/delete",method:"POST",params:{id:"@id"}},postLicense:{url:i+"/organizations/license",method:"POST",headers:{"Content-Type":void 0}},putLicense:{url:i+"/organizations/:id/license",method:"POST",headers:{"Content-Type":void 0}}}),a.organizationUsers=e(i+"/organizations/:orgId/users/:id",{},{get:{method:"GET",params:{id:"@id",orgId:"@orgId"}},list:{method:"GET",params:{orgId:"@orgId"}},listGroups:{url:i+"/organizations/:orgId/users/:id/groups",method:"GET",params:{id:"@id",orgId:"@orgId"},isArray:!0},invite:{url:i+"/organizations/:orgId/users/invite",method:"POST",params:{orgId:"@orgId"}},reinvite:{url:i+"/organizations/:orgId/users/:id/reinvite",method:"POST",params:{id:"@id",orgId:"@orgId"}},accept:{url:i+"/organizations/:orgId/users/:id/accept",method:"POST",params:{id:"@id",orgId:"@orgId"}},confirm:{url:i+"/organizations/:orgId/users/:id/confirm",method:"POST",params:{id:"@id",orgId:"@orgId"}},put:{method:"POST",params:{id:"@id",orgId:"@orgId"}},putGroups:{url:i+"/organizations/:orgId/users/:id/groups",method:"POST",params:{id:"@id",orgId:"@orgId"}},del:{url:i+"/organizations/:orgId/users/:id/delete",method:"POST",params:{id:"@id",orgId:"@orgId"}}}),a.collections=e(i+"/organizations/:orgId/collections/:id",{},{get:{method:"GET",params:{id:"@id",orgId:"@orgId"}},getDetails:{url:i+"/organizations/:orgId/collections/:id/details",method:"GET",params:{id:"@id",orgId:"@orgId"}},listMe:{url:i+"/collections?writeOnly=:writeOnly",method:"GET",params:{writeOnly:"@writeOnly"}},listOrganization:{method:"GET",params:{orgId:"@orgId"}},listUsers:{url:i+"/organizations/:orgId/collections/:id/users",method:"GET",params:{id:"@id",orgId:"@orgId"}},post:{method:"POST",params:{orgId:"@orgId"}},put:{method:"POST",params:{id:"@id",orgId:"@orgId"}},del:{url:i+"/organizations/:orgId/collections/:id/delete",method:"POST",params:{id:"@id",orgId:"@orgId"}},delUser:{url:i+"/organizations/:orgId/collections/:id/delete-user/:orgUserId",method:"POST",params:{id:"@id",orgId:"@orgId",orgUserId:"@orgUserId"}}}),a.groups=e(i+"/organizations/:orgId/groups/:id",{},{get:{method:"GET",params:{id:"@id",orgId:"@orgId"}},getDetails:{url:i+"/organizations/:orgId/groups/:id/details",method:"GET",params:{id:"@id",orgId:"@orgId"}},listOrganization:{method:"GET",params:{orgId:"@orgId"}},listUsers:{url:i+"/organizations/:orgId/groups/:id/users",method:"GET",params:{id:"@id",orgId:"@orgId"}},post:{method:"POST",params:{orgId:"@orgId"}},put:{method:"POST",params:{id:"@id",orgId:"@orgId"}},del:{url:i+"/organizations/:orgId/groups/:id/delete",method:"POST",params:{id:"@id",orgId:"@orgId"}},delUser:{url:i+"/organizations/:orgId/groups/:id/delete-user/:orgUserId",method:"POST",params:{id:"@id",orgId:"@orgId",orgUserId:"@orgUserId"}}}),a.accounts=e(i+"/accounts",{},{register:{url:i+"/accounts/register",method:"POST",params:{}},emailToken:{url:i+"/accounts/email-token",method:"POST",params:{}},email:{url:i+"/accounts/email",method:"POST",params:{}},verifyEmailToken:{url:i+"/accounts/verify-email-token",method:"POST",params:{}},verifyEmail:{url:i+"/accounts/verify-email",method:"POST",params:{}},postDeleteRecoverToken:{url:i+"/accounts/delete-recover-token",method:"POST",params:{}},postDeleteRecover:{url:i+"/accounts/delete-recover",method:"POST",params:{}},putPassword:{url:i+"/accounts/password",method:"POST",params:{}},getProfile:{url:i+"/accounts/profile",method:"GET",params:{}},putProfile:{url:i+"/accounts/profile",method:"POST",params:{}},getDomains:{url:i+"/accounts/domains",method:"GET",params:{}},putDomains:{url:i+"/accounts/domains",method:"POST",params:{}},postPasswordHint:{url:i+"/accounts/password-hint",method:"POST",params:{}},putSecurityStamp:{url:i+"/accounts/security-stamp",method:"POST",params:{}},putKeys:{url:i+"/accounts/keys",method:"POST",params:{}},putKey:{url:i+"/accounts/key",method:"POST",params:{}},import:{url:i+"/accounts/import",method:"POST",params:{}},postDelete:{url:i+"/accounts/delete",method:"POST",params:{}},putStorage:{url:i+"/accounts/storage",method:"POST",params:{}},putPayment:{url:i+"/accounts/payment",method:"POST",params:{}},putCancelPremium:{url:i+"/accounts/cancel-premium",method:"POST",params:{}},putReinstatePremium:{url:i+"/accounts/reinstate-premium",method:"POST",params:{}},getBilling:{url:i+"/accounts/billing",method:"GET",params:{}},postPremium:{url:i+"/accounts/premium",method:"POST",headers:{"Content-Type":void 0}},putLicense:{url:i+"/accounts/license",method:"POST",headers:{"Content-Type":void 0}}}),a.twoFactor=e(i+"/two-factor",{},{list:{method:"GET",params:{}},getEmail:{url:i+"/two-factor/get-email",method:"POST",params:{}},getU2f:{url:i+"/two-factor/get-u2f",method:"POST",params:{}},getDuo:{url:i+"/two-factor/get-duo",method:"POST",params:{}},getAuthenticator:{url:i+"/two-factor/get-authenticator",method:"POST",params:{}},getYubi:{url:i+"/two-factor/get-yubikey",method:"POST",params:{}},sendEmail:{url:i+"/two-factor/send-email",method:"POST",params:{}},sendEmailLogin:{url:i+"/two-factor/send-email-login",method:"POST",params:{}},putEmail:{url:i+"/two-factor/email",method:"POST",params:{}},putU2f:{url:i+"/two-factor/u2f",method:"POST",params:{}},putAuthenticator:{url:i+"/two-factor/authenticator",method:"POST",params:{}},putDuo:{url:i+"/two-factor/duo",method:"POST",params:{}},putYubi:{url:i+"/two-factor/yubikey",method:"POST",params:{}},disable:{url:i+"/two-factor/disable",method:"POST",params:{}},recover:{url:i+"/two-factor/recover",method:"POST",params:{}},getRecover:{url:i+"/two-factor/get-recover",method:"POST",params:{}}}),a.settings=e(i+"/settings",{},{getDomains:{url:i+"/settings/domains",method:"GET",params:{}},putDomains:{url:i+"/settings/domains",method:"POST",params:{}}}),a.users=e(i+"/users/:id",{},{getPublicKey:{url:i+"/users/:id/public-key",method:"GET",params:{id:"@id"}}}),a.events=e(i+"/events",{},{list:{method:"GET",params:{}},listOrganization:{url:i+"/organizations/:orgId/events",method:"GET",params:{id:"@orgId"}},listCipher:{url:i+"/ciphers/:id/events",method:"GET",params:{id:"@id"}},listOrganizationUser:{url:i+"/organizations/:orgId/users/:id/events",method:"GET",params:{orgId:"@orgId",id:"@id"}}}),a.identity=e(s+"/connect",{},{token:{url:s+"/connect/token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=utf-8","Device-Type":o.getDeviceType()},transformRequest:function(e){return r(e)},skipAuthorization:!0,params:{}}}),a.hibp=e("https://haveibeenpwned.com/api/v2/breachedaccount/:email",{},{get:{method:"GET",params:{email:"@email"},isArray:!0}}),a}]),angular.module("bit.services").factory("authService",["cryptoService","apiService","tokenService","$q","jwtHelper","$rootScope","constants",function(e,t,n,r,o,a,i){var s={},l=null;s.logIn=function(o,a,l,c,u){o=o.toLowerCase();var d,p=r.defer();return e.makeKeyAndHash(o,a).then(function(e){d=e;var r={username:o,password:e.hash,grant_type:"password",scope:"api offline_access",client_id:"web"};return l&&null!=c?(u=u||!1!==u,r.twoFactorToken=l,r.twoFactorProvider=c,r.twoFactorRemember=u?"1":"0"):n.getTwoFactorToken(o)&&(r.twoFactorToken=n.getTwoFactorToken(o),r.twoFactorProvider=i.twoFactorProvider.remember,r.twoFactorRemember="0"),t.identity.token(r).$promise}).then(function(t){if(t&&t.access_token)return n.setToken(t.access_token),n.setRefreshToken(t.refresh_token),e.setKey(d.key),t.TwoFactorToken&&n.setTwoFactorToken(t.TwoFactorToken,o),t.Key&&e.setEncKey(t.Key,d.key),t.PrivateKey?(e.setPrivateKey(t.PrivateKey),!0):e.makeKeyPair()}).then(function(n){if(!0!==n)return e.setPrivateKey(n.privateKeyEnc),t.accounts.putKeys({publicKey:n.publicKey,encryptedPrivateKey:n.privateKeyEnc}).$promise}).then(function(){return s.setUserProfile()}).then(function(){p.resolve()},function(e){s.logOut(),400===e.status&&e.data.TwoFactorProviders2&&Object.keys(e.data.TwoFactorProviders2).length?(n.clearTwoFactorToken(o),p.resolve(e.data.TwoFactorProviders2)):p.reject(e)}),p.promise},s.logOut=function(){n.clearTokens(),e.clearKeys(),a.vaultCiphers=a.vaultFolders=a.vaultCollections=null,l=null},s.getUserProfile=function(){if(!l)return s.setUserProfile();var e=r.defer();return e.resolve(l),e.promise};var c=null;return s.setUserProfile=function(){return c&&0===c.promise.$$state.status?c.promise:(c=r.defer(),n.getToken()?(t.accounts.getProfile({},function(t){if(l={id:t.Id,email:t.Email,emailVerified:t.EmailVerified,premium:t.Premium,extended:{name:t.Name,twoFactorEnabled:t.TwoFactorEnabled,culture:t.Culture}},t.Organizations){for(var n={},r=0;r<t.Organizations.length;r++)n[t.Organizations[r].Id]={id:t.Organizations[r].Id,name:t.Organizations[r].Name,key:t.Organizations[r].Key,status:t.Organizations[r].Status,type:t.Organizations[r].Type,enabled:t.Organizations[r].Enabled,maxCollections:t.Organizations[r].MaxCollections,maxStorageGb:t.Organizations[r].MaxStorageGb,seats:t.Organizations[r].Seats,useGroups:t.Organizations[r].UseGroups,useDirectory:t.Organizations[r].UseDirectory,useEvents:t.Organizations[r].UseEvents,useTotp:t.Organizations[r].UseTotp};l.organizations=n,e.setOrgKeys(n),c.resolve(l)}},function(e){c.reject(e)}),c.promise):(c.reject(),c.promise))},s.addProfileOrganizationOwner=function(t,n){return s.getUserProfile().then(function(r){if(r){r.organizations||(r.organizations={});var o={id:t.Id,name:t.Name,key:n,status:2,type:0,enabled:!0,maxCollections:t.MaxCollections,maxStorageGb:t.MaxStorageGb,seats:t.Seats,useGroups:t.UseGroups,useDirectory:t.UseDirectory,useEvents:t.UseEvents,useTotp:t.UseTotp};r.organizations[o.id]=o,l=r,e.addOrgKey(o.id,o.key)}})},s.removeProfileOrganization=function(t){return s.getUserProfile().then(function(n){n&&(n.organizations&&n.organizations.hasOwnProperty(t)&&(delete n.organizations[t],l=n),e.clearOrgKey(t))})},s.updateProfileOrganization=function(e){return s.getUserProfile().then(function(t){t&&t.organizations&&e.Id in t.organizations&&(t.organizations[e.Id].name=e.Name,l=t)})},s.updateProfilePremium=function(e){return s.getUserProfile().then(function(t){t&&(t.premium=e,l=t)})},s.isAuthenticated=function(){return null!==n.getToken()},s.refreshAccessToken=function(){var e=n.getRefreshToken();return e?t.identity.token({grant_type:"refresh_token",client_id:"web",refresh_token:e}).$promise.then(function(e){return n.setToken(e.access_token),n.setRefreshToken(e.refresh_token),e.access_token},function(e){}):r(function(e,t){e(null)})},s}]),angular.module("bit.services").factory("cipherService",["cryptoService","apiService","$q","$window","constants","appSettings","$localStorage",function(e,t,n,r,o,a,i){var s={disableWebsiteIcons:i.disableWebsiteIcons};function l(t,n){return t&&""!==t?e.encrypt(t,n):null}return s.decryptCiphers=function(e){if(!e)throw"encryptedCiphers is undefined or null";for(var t=[],n=0;n<e.length;n++)t.push(s.decryptCipher(e[n]));return t},s.decryptCipher=function(t){if(!t)throw"encryptedCipher is undefined or null";var n=null;t.OrganizationId&&(n=e.getOrgKey(t.OrganizationId));var r,a={id:t.Id,organizationId:t.OrganizationId,collectionIds:t.CollectionIds||[],type:t.Type,name:e.decrypt(t.Name,n),notes:s.decryptProperty(t.Notes,n,!0,!1),fields:s.decryptFields(n,t.Fields),folderId:t.FolderId,favorite:t.Favorite,edit:t.Edit,organizationUseTotp:t.OrganizationUseTotp,attachments:null,icon:null};switch(a.type){case o.cipherType.login:if(a.login={username:s.decryptProperty(t.Login.Username,n,!0,!1),password:s.decryptProperty(t.Login.Password,n,!0,!1),totp:s.decryptProperty(t.Login.Totp,n,!0,!1),uris:null},t.Login.Uris)for(a.login.uris=[],r=0;r<t.Login.Uris.length;r++)a.login.uris.push({uri:s.decryptProperty(t.Login.Uris[r].Uri,n,!0,!1),match:t.Login.Uris[r].Match});a.icon="fa-globe";break;case o.cipherType.secureNote:a.secureNote={type:t.SecureNote.Type},a.icon="fa-sticky-note-o";break;case o.cipherType.card:a.card={cardholderName:s.decryptProperty(t.Card.CardholderName,n,!0,!1),number:s.decryptProperty(t.Card.Number,n,!0,!1),brand:s.decryptProperty(t.Card.Brand,n,!0,!1),expMonth:s.decryptProperty(t.Card.ExpMonth,n,!0,!1),expYear:s.decryptProperty(t.Card.ExpYear,n,!0,!1),code:s.decryptProperty(t.Card.Code,n,!0,!1)},a.icon="fa-credit-card";break;case o.cipherType.identity:a.identity={title:s.decryptProperty(t.Identity.Title,n,!0,!1),firstName:s.decryptProperty(t.Identity.FirstName,n,!0,!1),middleName:s.decryptProperty(t.Identity.MiddleName,n,!0,!1),lastName:s.decryptProperty(t.Identity.LastName,n,!0,!1),address1:s.decryptProperty(t.Identity.Address1,n,!0,!1),address2:s.decryptProperty(t.Identity.Address2,n,!0,!1),address3:s.decryptProperty(t.Identity.Address3,n,!0,!1),city:s.decryptProperty(t.Identity.City,n,!0,!1),state:s.decryptProperty(t.Identity.State,n,!0,!1),postalCode:s.decryptProperty(t.Identity.PostalCode,n,!0,!1),country:s.decryptProperty(t.Identity.Country,n,!0,!1),company:s.decryptProperty(t.Identity.Company,n,!0,!1),email:s.decryptProperty(t.Identity.Email,n,!0,!1),phone:s.decryptProperty(t.Identity.Phone,n,!0,!1),ssn:s.decryptProperty(t.Identity.SSN,n,!0,!1),username:s.decryptProperty(t.Identity.Username,n,!0,!1),passportNumber:s.decryptProperty(t.Identity.PassportNumber,n,!0,!1),licenseNumber:s.decryptProperty(t.Identity.LicenseNumber,n,!0,!1)},a.icon="fa-id-card-o"}if(!t.Attachments)return a;for(a.attachments=[],r=0;r<t.Attachments.length;r++)a.attachments.push(s.decryptAttachment(n,t.Attachments[r]));return a},s.decryptCipherPreview=function(t){if(!t)throw"encryptedCipher is undefined or null";var n=null;t.OrganizationId&&(n=e.getOrgKey(t.OrganizationId));var r={id:t.Id,organizationId:t.OrganizationId,collectionIds:t.CollectionIds||[],type:t.Type,name:s.decryptProperty(t.Name,n,!1,!0),folderId:t.FolderId,favorite:t.Favorite,edit:t.Edit,organizationUseTotp:t.OrganizationUseTotp,hasAttachments:!!t.Attachments&&t.Attachments.length>0,meta:{},icon:null};switch(r.type){case o.cipherType.login:r.subTitle=s.decryptProperty(t.Login.Username,n,!0,!0),r.meta.password=s.decryptProperty(t.Login.Password,n,!0,!0),r.meta.uri=null,t.Login.Uris&&t.Login.Uris.length&&(r.meta.uri=s.decryptProperty(t.Login.Uris[0].Uri,n,!0,!0)),function(e,t,n){if(!s.disableWebsiteIcons&&t){var r=t,o=!1;if(0===r.indexOf("androidapp://")?e.icon="fa-android":0===r.indexOf("iosapp://")?e.icon="fa-apple":-1===r.indexOf("://")&&r.indexOf(".")>-1?(r="http://"+r,o=!0):o=0===r.indexOf("http")&&r.indexOf(".")>-1,n&&o)try{var i=new URL(r);e.meta.image=a.iconsUri+"/"+i.hostname+"/icon.png"}catch(e){}}e.icon||(e.icon="fa-globe")}(r,r.meta.uri,!0);break;case o.cipherType.secureNote:r.subTitle=null,r.icon="fa-sticky-note-o";break;case o.cipherType.card:r.subTitle="",r.meta.number=s.decryptProperty(t.Card.Number,n,!0,!0);var i=s.decryptProperty(t.Card.Brand,n,!0,!0);i&&(r.subTitle=i),r.meta.number&&r.meta.number.length>=4&&(""!==r.subTitle&&(r.subTitle+=", "),r.subTitle+="*"+r.meta.number.substr(r.meta.number.length-4)),r.icon="fa-credit-card";break;case o.cipherType.identity:var l=s.decryptProperty(t.Identity.FirstName,n,!0,!0),c=s.decryptProperty(t.Identity.LastName,n,!0,!0);r.subTitle="",l&&(r.subTitle=l),c&&(""!==r.subTitle&&(r.subTitle+=" "),r.subTitle+=c),r.icon="fa-id-card-o"}return""===r.subTitle&&(r.subTitle=null),r},s.decryptAttachment=function(t,n){if(!n)throw"encryptedAttachment is undefined or null";return{id:n.Id,url:n.Url,fileName:e.decrypt(n.FileName,t),size:n.SizeName}},s.downloadAndDecryptAttachment=function(t,o,a){var i=n.defer(),s=new XMLHttpRequest;return s.open("GET",o.url,!0),s.responseType="arraybuffer",s.onload=function(n){s.response?e.decryptFromBytes(s.response,t).then(function(e){if(a){var t=new Blob([e]);if(r.navigator.msSaveOrOpenBlob)r.navigator.msSaveBlob(t,o.fileName);else{var n=r.document.createElement("a");n.href=r.URL.createObjectURL(t),n.download=o.fileName,r.document.body.appendChild(n),n.click(),r.document.body.removeChild(n)}}i.resolve(new Uint8Array(e))}):i.reject("No response")},s.send(null),i.promise},s.decryptFields=function(e,t){var n=[];if(t)for(var r=0;r<t.length;r++)n.push(s.decryptField(e,t[r]));return n},s.decryptField=function(t,n){if(!n)throw"encryptedField is undefined or null";return{type:n.Type.toString(),name:n.Name&&""!==n.Name?e.decrypt(n.Name,t):null,value:n.Value&&""!==n.Value?e.decrypt(n.Value,t):null}},s.decryptFolders=function(e){if(!e)throw"encryptedFolders is undefined or null";for(var t=[],n=0;n<e.length;n++)t.push(s.decryptFolder(e[n]));return t},s.decryptFolder=function(t){if(!t)throw"encryptedFolder is undefined or null";return{id:t.Id,name:e.decrypt(t.Name)}},s.decryptFolderPreview=function(e){if(!e)throw"encryptedFolder is undefined or null";return{id:e.Id,name:s.decryptProperty(e.Name,null,!1,!0)}},s.decryptCollections=function(e,t,n){if(!e)throw"encryptedCollections is undefined or null";for(var r=[],o=0;o<e.length;o++)r.push(s.decryptCollection(e[o],t,n));return r},s.decryptCollection=function(t,n,r){if(!t)throw"encryptedCollection is undefined or null";r=!0===r,n=n||t.OrganizationId;var o=e.getOrgKey(n);return{id:t.Id,name:r?s.decryptProperty(t.Name,o,!1,!0):e.decrypt(t.Name,o)}},s.decryptProperty=function(t,n,r,o){if(r&&(!t||""===t))return null;try{t=e.decrypt(t,n)}catch(e){t=null}return t||(o?"[error: cannot decrypt]":null)},s.encryptCiphers=function(e,t){if(!e)throw"unencryptedCiphers is undefined or null";for(var n=[],r=0;r<e.length;r++)n.push(s.encryptCipher(e[r],null,t));return n},s.encryptCipher=function(t,n,r,a){if(!t)throw"unencryptedCipher is undefined or null";t.organizationId&&(r=r||e.getOrgKey(t.organizationId));var i,c={id:t.id,type:n||t.type,organizationId:t.organizationId||null,folderId:""===t.folderId?null:t.folderId,favorite:null!==t.favorite&&t.favorite,name:e.encrypt(t.name,r),notes:l(t.notes,r),fields:s.encryptFields(t.fields,r)};switch(c.type){case o.cipherType.login:var u=t.login;if(c.login={username:l(u.username,r),password:l(u.password,r),totp:l(u.totp,r)},u.uris&&u.uris.length)for(c.login.uris=[],i=0;i<u.uris.length;i++)c.login.uris.push({uri:l(u.uris[i].uri,r),match:u.uris[i].match});break;case o.cipherType.secureNote:c.secureNote={type:t.secureNote.type};break;case o.cipherType.card:var d=t.card;c.card={cardholderName:l(d.cardholderName,r),brand:l(d.brand,r),number:l(d.number,r),expMonth:l(d.expMonth,r),expYear:l(d.expYear,r),code:l(d.code,r)};break;case o.cipherType.identity:var p=t.identity;c.identity={title:l(p.title,r),firstName:l(p.firstName,r),middleName:l(p.middleName,r),lastName:l(p.lastName,r),address1:l(p.address1,r),address2:l(p.address2,r),address3:l(p.address3,r),city:l(p.city,r),state:l(p.state,r),postalCode:l(p.postalCode,r),country:l(p.country,r),company:l(p.company,r),email:l(p.email,r),phone:l(p.phone,r),ssn:l(p.ssn,r),username:l(p.username,r),passportNumber:l(p.passportNumber,r),licenseNumber:l(p.licenseNumber,r)}}if(t.attachments&&a)for(c.attachments={},i=0;i<t.attachments.length;i++)c.attachments[t.attachments[i].id]=e.encrypt(t.attachments[i].fileName,r);return c},s.encryptAttachmentFile=function(t,r){var o=n.defer();if(!(r.size>104857600)){var a=new FileReader;return a.readAsArrayBuffer(r),a.onload=function(n){e.encryptToBytes(n.target.result,t).then(function(n){o.resolve({fileName:e.encrypt(r.name,t),data:new Uint8Array(n),size:r.size})})},a.onerror=function(e){o.reject("Error reading file.")},o.promise}o.reject("Maximum file size is 100 MB.")},s.encryptFields=function(e,t){if(!e||!e.length)return null;for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(s.encryptField(e[r],t));return n},s.encryptField=function(t,n){if(!t)throw"unencryptedField is undefined or null";return{type:parseInt(t.type),name:t.name?e.encrypt(t.name,n):null,value:t.value?e.encrypt(t.value.toString(),n):null}},s.encryptFolders=function(e,t){if(!e)throw"unencryptedFolders is undefined or null";for(var n=[],r=0;r<e.length;r++)n.push(s.encryptFolder(e[r],t));return n},s.encryptFolder=function(t,n){if(!t)throw"unencryptedFolder is undefined or null";return{id:t.id,name:e.encrypt(t.name,n)}},s.encryptCollections=function(e,t){if(!e)throw"unencryptedCollections is undefined or null";for(var n=[],r=0;r<e.length;r++)n.push(s.encryptCollection(e[r],t));return n},s.encryptCollection=function(t,n){if(!t)throw"unencryptedCollection is undefined or null";return{id:t.id,name:e.encrypt(t.name,e.getOrgKey(n))}},s}]),angular.module("bit.services").factory("cryptoService",["$sessionStorage","constants","$q","$window",function(e,t,n,r){var o,a,i,s,l,c,u={},d=void 0!==r.crypto?r.crypto:null,p=d&&void 0!==r.crypto.subtle?r.crypto.subtle:null;function m(e,t,n,r){return e="string"==typeof e?b(e):e,t="string"==typeof t?b(t):t,p.importKey("raw",e.buffer,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]).then(function(e){return p.deriveKey({name:"PBKDF2",salt:t.buffer,iterations:n,hash:{name:"SHA-256"}},e,{name:"AES-CBC",length:r},!0,["encrypt","decrypt"])}).then(function(e){return p.exportKey("raw",e)})}function g(e,t,n){var r=forge.hmac.create();r.start("sha256",t),r.update(e);var o=r.digest();return n?forge.util.encode64(o.getBytes()):o.getBytes()}function f(e,t){return p.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]).then(function(t){return p.sign({name:"HMAC",hash:{name:"SHA-256"}},t,e)})}function h(e,t){var n=forge.hmac.create();return n.start("sha256",function(e){var t=new Uint32Array(e/4);d.getRandomValues(t);for(var n=forge.util.createBuffer(),r=0;r<t.length;r++)n.putInt32(t[r]);return n.getBytes()}(32)),n.update(e),e=n.digest().getBytes(),n.start(null,null),n.update(t),e===(t=n.digest().getBytes())}function v(e,n,r){if(n&&(e=forge.util.decode64(e)),!e)throw"Must provide keyBytes";var o=forge.util.createBuffer(e);if(!o||0===o.length())throw"Couldn't make buffer";var a=o.length();if(null==r)if(32===a)r=t.encType.AesCbc256_B64;else{if(64!==a)throw"Unable to determine encType.";r=t.encType.AesCbc256_HmacSha256_B64}if(this.key=e,this.keyB64=forge.util.encode64(e),this.encType=r,r===t.encType.AesCbc256_B64&&32===a)this.encKey=e,this.macKey=null;else if(r===t.encType.AesCbc128_HmacSha256_B64&&32===a)this.encKey=o.getBytes(16),this.macKey=o.getBytes(16);else{if(r!==t.encType.AesCbc256_HmacSha256_B64||64!==a)throw"Unsupported encType/key length.";this.encKey=o.getBytes(32),this.macKey=o.getBytes(32)}}function y(e){for(var t="",n=new Uint8Array(e),o=0;o<n.byteLength;o++)t+=String.fromCharCode(n[o]);return r.btoa(t)}function b(e){for(var t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length),r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function w(e,t,n){if(e.slice)return e.slice(t,n);if(e=e.buffer,void 0===t&&(t=0),void 0===n&&(n=e.byteLength),t=Math.floor(t),n=Math.floor(n),t<0&&(t+=e.byteLength),n<0&&(n+=e.byteLength),t=Math.min(Math.max(0,t),e.byteLength),(n=Math.min(Math.max(0,n),e.byteLength))-t<=0)return new ArrayBuffer(0);var r=new ArrayBuffer(n-t),o=new Uint8Array(r),a=new Uint8Array(e,t,n-t);return o.set(a),new Uint8Array(r)}return u.setKey=function(t){o=t,e.key=o.keyB64},u.setEncKey=function(t,n,r){if(r)return a=t,void(e.encKey=a.keyB64);try{var o=u.decrypt(t,n,"raw");e.encKey=forge.util.encode64(o),a=new v(o)}catch(e){console.log("Cannot set enc key. Decryption failed.")}},u.setPrivateKey=function(t,n){try{var r=u.decrypt(t,n,"raw");e.privateKey=forge.util.encode64(r),l=forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(r))}catch(e){console.log("Cannot set private key. Decryption failed.")}},u.setOrgKeys=function(t,n){if(t&&0!==Object.keys(t).length){u.clearOrgKeys();var r={},o={},a=!1;for(var i in t)if(t.hasOwnProperty(i))try{var s=new v(u.rsaDecrypt(t[i].key,n));o[i]=s,r[i]=s.keyB64,a=!0}catch(e){console.log("Cannot set org key for "+i+". Decryption failed.")}a?e.orgKeys=r:o=null}},u.addOrgKey=function(t,n,r){(s=u.getOrgKeys())||(s={});var o=e.orgKeys;o||(o={});try{var a=new v(u.rsaDecrypt(n,r));s[t]=a,o[t]=a.keyB64}catch(e){s=null,console.log("Cannot set org key. Decryption failed.")}e.orgKeys=o},u.getKey=function(){if(!o&&e.key&&(o=new v(e.key,!0)),!o)throw"key unavailable";return o},u.getEncKey=function(){return!a&&e.encKey&&(a=new v(e.encKey,!0)),a},u.getPrivateKey=function(t){if(t=t||"native",l){if("raw"===t){var n=forge.pki.privateKeyToAsn1(l),r=forge.pki.wrapRsaPrivateKey(n);return forge.asn1.toDer(r).getBytes()}return l}if(e.privateKey){var o=forge.util.decode64(e.privateKey);if(l=forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(o)),"raw"===t)return o}return l},u.getPublicKey=function(){if(c)return c;var e=u.getPrivateKey();return e?c=forge.pki.setRsaPublicKey(e.n,e.e):null},u.getOrgKeys=function(){if(s)return s;if(e.orgKeys){var t={},n=!1;for(var r in e.orgKeys)e.orgKeys.hasOwnProperty(r)&&(t[r]=new v(e.orgKeys[r],!0),n=!0);n&&(s=t)}return s},u.getOrgKey=function(e){var t=u.getOrgKeys();return t&&e in t?t[e]:null},u.clearKey=function(){o=null,i=null,delete e.key},u.clearEncKey=function(){a=null,delete e.encKey},u.clearKeyPair=function(){l=null,c=null,delete e.privateKey},u.clearOrgKeys=function(){s=null,delete e.orgKeys},u.clearOrgKey=function(t){s.hasOwnProperty(t)&&delete s[t],e.orgKeys.hasOwnProperty(t)&&delete e.orgKeys[t]},u.clearKeys=function(){u.clearKey(),u.clearEncKey(),u.clearKeyPair(),u.clearOrgKeys()},u.makeKey=function(e,t){if(r.cryptoShimmed||-1!==r.navigator.userAgent.indexOf("Edge")){var o=n.defer(),a=forge.pbkdf2(forge.util.encodeUtf8(e),forge.util.encodeUtf8(t),5e3,32,"sha256");return o.resolve(new v(a)),o.promise}return m(e,t,5e3,256).then(function(e){return new v(y(e),!0)})},u.makeEncKey=function(e){var t=forge.random.getBytesSync(64),n=u.encrypt(t,e,"raw");return{encKey:new v(t),encKeyEnc:n}},u.makeKeyPair=function(e){var t=n.defer();return forge.pki.rsa.generateKeyPair({bits:2048,workers:2,workerScript:"/lib/forge/prime.worker.min.js"},function(n,r){if(n)t.reject(n);else{var o=forge.pki.privateKeyToAsn1(r.privateKey),a=forge.pki.wrapRsaPrivateKey(o),i=forge.asn1.toDer(a).getBytes(),s=u.encrypt(i,e,"raw"),l=forge.pki.publicKeyToAsn1(r.publicKey),c=forge.asn1.toDer(l).getBytes();t.resolve({publicKey:forge.util.encode64(c),privateKeyEnc:s})}}),t.promise},u.makeShareKey=function(){var e=forge.random.getBytesSync(64);return{key:new v(e),ct:u.rsaEncryptMe(e)}},u.hashPassword=function(e,t){if(t||(t=u.getKey()),!e||!t)throw"Invalid parameters.";if(r.cryptoShimmed||-1!==r.navigator.userAgent.indexOf("Edge")){var o=n.defer(),a=forge.pbkdf2(t.key,forge.util.encodeUtf8(e),1,32,"sha256");return o.resolve(forge.util.encode64(a)),o.promise}var i=t.getBuffers();return m(new Uint8Array(i.key),e,1,256).then(function(e){return y(e)})},u.makeKeyAndHash=function(e,t){var n;return e=e.toLowerCase(),u.makeKey(t,e).then(function(e){return n=e,u.hashPassword(t,e)}).then(function(e){return{key:n,hash:e}})},u.encrypt=function(e,t,n){var r=function(e,t,n){if(!(t=t||u.getEncKey()||u.getKey()))throw"Encryption key unavailable.";n=n||"utf8";var r=forge.util.createBuffer(e,n),o=forge.random.getBytesSync(16),a=forge.cipher.createCipher("AES-CBC",t.encKey);a.start({iv:o}),a.update(r),a.finish();var i=a.output.getBytes(),s=null;t.macKey&&(s=g(o+i,t.macKey,!1));return{iv:o,ct:i,mac:s,key:t,plainValueEncoding:n}}(e,t,n),o=forge.util.encode64(r.iv)+"|"+forge.util.encode64(r.ct);r.mac&&(o=o+"|"+forge.util.encode64(r.mac));return r.key.encType+"."+o},u.encryptToBytes=function(e,t){return function(e,t){if(!(t=t||u.getEncKey()||u.getKey()))throw"Encryption key unavailable.";var n={iv:new Uint8Array(16),ct:null,mac:null,key:t},r=t.getBuffers();return d.getRandomValues(n.iv),p.importKey("raw",r.encKey,{name:"AES-CBC"},!1,["encrypt"]).then(function(t){return p.encrypt({name:"AES-CBC",iv:n.iv},t,e)}).then(function(e){if(n.ct=new Uint8Array(e),!r.macKey)return null;var t=new Uint8Array(n.iv.length+n.ct.length);return t.set(n.iv,0),t.set(n.ct,n.iv.length),f(t.buffer,r.macKey)}).then(function(e){return e&&(n.mac=new Uint8Array(e)),n})}(e,t).then(function(e){var t=0;e.mac&&(t=e.mac.length);var n=new Uint8Array(1+e.iv.length+t+e.ct.length);return n.set([e.key.encType]),n.set(e.iv,1),e.mac&&n.set(e.mac,1+e.iv.length),n.set(e.ct,1+e.iv.length+t),n.buffer})},u.rsaEncrypt=function(e,n,r){if(!(n=n||u.getPublicKey()))throw"Public key unavailable.";if("string"==typeof n){var o=forge.util.decode64(n);n=forge.pki.publicKeyFromAsn1(forge.asn1.fromDer(o))}var a=n.encrypt(e,"RSA-OAEP",{md:forge.md.sha1.create()}),i=forge.util.encode64(a);if(r&&r.macKey){var s=g(a,r.macKey,!0);return t.encType.Rsa2048_OaepSha1_HmacSha256_B64+"."+i+"|"+s}return t.encType.Rsa2048_OaepSha1_B64+"."+i},u.rsaEncryptMe=function(e){return u.rsaEncrypt(e,u.getPublicKey(),u.getEncKey())},u.decrypt=function(e,n,r){try{n=n||u.getEncKey()||u.getKey();var o,a,s=e.split(".");if(2===s.length)try{o=parseInt(s[0]),a=s[1].split("|")}catch(e){return console.error("Cannot parse headerPieces."),null}else o=3===(a=e.split("|")).length?t.encType.AesCbc128_HmacSha256_B64:t.encType.AesCbc256_B64;if(o===t.encType.AesCbc128_HmacSha256_B64&&n.encType===t.encType.AesCbc256_B64&&(n=i=i||new v(n.key,!1,t.encType.AesCbc128_HmacSha256_B64)),o!==n.encType)throw"encType unavailable.";switch(o){case t.encType.AesCbc128_HmacSha256_B64:case t.encType.AesCbc256_HmacSha256_B64:if(3!==a.length)return console.error("Enc type ("+o+") not valid."),null;break;case t.encType.AesCbc256_B64:if(2!==a.length)return console.error("Enc type ("+o+") not valid."),null;break;default:return console.error("Enc type ("+o+") not supported."),null}var l=forge.util.decode64(a[0]),c=forge.util.decode64(a[1]);if(n.macKey&&a.length>2)if(!h(forge.util.decode64(a[2]),g(l+c,n.macKey,!1)))return console.error("MAC failed."),null;var d=forge.util.createBuffer(c),p=forge.cipher.createDecipher("AES-CBC",n.encKey);return p.start({iv:l}),p.update(d),p.finish(),"utf8"===(r=r||"utf8")?p.output.toString("utf8"):p.output.getBytes()}catch(e){throw console.error("Caught unhandled error in decrypt: "+e),e}},u.decryptFromBytes=function(e,n){try{if(!e)throw"no encBuf.";var r=new Uint8Array(e),o=r[0],a=null,i=null,s=null;switch(o){case t.encType.AesCbc128_HmacSha256_B64:case t.encType.AesCbc256_HmacSha256_B64:if(r.length<=49)return console.error("Enc type ("+o+") not valid."),null;i=w(r,1,17),s=w(r,17,49),a=w(r,49);break;case t.encType.AesCbc256_B64:if(r.length<=17)return console.error("Enc type ("+o+") not valid."),null;i=w(r,1,17),a=w(r,17);break;default:return console.error("Enc type ("+o+") not supported."),null}return function(e,t,n,r,o){if(!(o=o||u.getEncKey()||u.getKey()))throw"Encryption key unavailable.";if(o.macKey&&!r)throw"macBuf required for this type of key.";if(e!==o.encType)throw"encType unavailable.";var a=o.getBuffers(),i=null;return p.importKey("raw",a.encKey,{name:"AES-CBC"},!1,["decrypt"]).then(function(e){if(i=e,!o.macKey||!r)return null;var s=new Uint8Array(n.byteLength+t.byteLength);return s.set(new Uint8Array(n),0),s.set(new Uint8Array(t),n.byteLength),f(s.buffer,a.macKey)}).then(function(e){return null===e?null:(t=r,n=e,i=new Uint8Array(32),d.getRandomValues(i),window.crypto.subtle.importKey("raw",i.buffer,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]).then(function(e){return a=e,window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-256"}},a,t)}).then(function(e){return o=e,window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-256"}},a,n)}).then(function(e){if(o.byteLength!==e.byteLength)return!1;for(var t=new Uint8Array(o),n=new Uint8Array(e),r=0;r<n.length;r++)if(t[r]!==n[r])return!1;return!0}));var t,n,o,a,i}).then(function(e){return!1===e?(console.error("MAC failed."),null):p.decrypt({name:"AES-CBC",iv:n},i,t)})}(o,a.buffer,i.buffer,s?s.buffer:null,n)}catch(e){throw console.error("Caught unhandled error in decryptFromBytes: "+e),e}},u.rsaDecrypt=function(e,n,r){if(n=n||u.getPrivateKey(),r=r||u.getEncKey(),!n)throw"Private key unavailable.";var o,a,i=e.split(".");if(1===i.length)o=t.encType.Rsa2048_OaepSha256_B64,a=[i[0]];else if(2===i.length)try{o=parseInt(i[0]),a=i[1].split("|")}catch(e){return null}switch(o){case t.encType.Rsa2048_OaepSha256_B64:case t.encType.Rsa2048_OaepSha1_B64:if(1!==a.length)return null;break;case t.encType.Rsa2048_OaepSha256_HmacSha256_B64:case t.encType.Rsa2048_OaepSha1_HmacSha256_B64:if(2!==a.length)return null;break;default:return null}var s,l=forge.util.decode64(a[0]);if(r&&r.macKey&&a.length>1&&!h(forge.util.decode64(a[1]),g(l,r.macKey,!1)))return console.error("MAC failed."),null;if(o===t.encType.Rsa2048_OaepSha256_B64||o===t.encType.Rsa2048_OaepSha256_HmacSha256_B64)s=forge.md.sha256.create();else{if(o!==t.encType.Rsa2048_OaepSha1_B64&&o!==t.encType.Rsa2048_OaepSha1_HmacSha256_B64)throw"encType unavailable.";s=forge.md.sha1.create()}return n.decrypt(l,"RSA-OAEP",{md:s})},v.prototype.getBuffers=function(){if(this.keyBuf)return this.keyBuf;var e=function(e){for(var t=r.atob(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}(this.keyB64),t={key:e.buffer};return this.macKey?(t.encKey=w(e,0,e.length/2).buffer,t.macKey=w(e,e.length/2).buffer):(t.encKey=e.buffer,t.macKey=null),this.keyBuf=t,this.keyBuf},u}]),angular.module("bit.services").factory("eventService",["constants","$filter",function(e,t){var n={};function r(e){var t=e.CipherId.substring(0,8);return e.OrganizationId?'<a title="View item '+e.CipherId+'" ui-sref="backend.org.vault({orgId:\''+e.OrganizationId+"',search:'"+t+"',viewEvents:'"+e.CipherId+"'})\"><code>"+t+"</code></a>":"<code>"+t+"</code>"}function o(e){var t=e.GroupId.substring(0,8);return'<a title="View group '+e.GroupId+'" ui-sref="backend.org.groups({orgId:\''+e.OrganizationId+"',search:'"+t+"'})\"><code>"+t+"</code></a>"}function a(e){var t=e.CollectionId.substring(0,8);return'<a title="View collection '+e.CollectionId+'" ui-sref="backend.org.collections({orgId:\''+e.OrganizationId+"',search:'"+t+"'})\"><code>"+t+"</code></a>"}function i(e){var t=e.OrganizationUserId.substring(0,8);return'<a title="View user '+e.OrganizationUserId+'" ui-sref="backend.org.people({orgId:\''+e.OrganizationId+"',search:'"+t+"'})\"><code>"+t+"</code></a>"}return n.getDefaultDateFilters=function(){var e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59);return e.setDate(e.getDate()-30),{start:new Date(e.getFullYear(),e.getMonth(),e.getDate(),0,0),end:t}},n.formatDateFilters=function(e,n){var r={start:null,end:null,error:null};try{var o="yyyy-MM-ddTHH:mm";r.start=t("date")(e,o+"Z","UTC"),r.end=t("date")(n,o+":59.999Z","UTC")}catch(e){}return(!r.start||!r.end||r.end<r.start)&&(r.error="Invalid date range."),r},n.getEventInfo=function(t,n){n=n||{cipherInfo:!0};var s=function(t){var n={icon:"fa-globe",name:"Unknown"};switch(t.DeviceType){case e.deviceType.android:n.icon="fa-android",n.name="Mobile App - Android";break;case e.deviceType.ios:n.icon="fa-apple",n.name="Mobile App - iOS";break;case e.deviceType.uwp:n.icon="fa-windows",n.name="Mobile App - Windows";break;case e.deviceType.chromeExt:n.icon="fa-chrome",n.name="Extension - Chrome";break;case e.deviceType.firefoxExt:n.icon="fa-firefox",n.name="Extension - Firefox";break;case e.deviceType.operaExt:n.icon="fa-opera",n.name="Extension - Opera";break;case e.deviceType.edgeExt:n.icon="fa-edge",n.name="Extension - Edge";break;case e.deviceType.vivaldiExt:n.icon="fa-puzzle-piece",n.name="Extension - Vivaldi";break;case e.deviceType.windowsDesktop:n.icon="fa-windows",n.name="Desktop - Windows";break;case e.deviceType.macOsDesktop:n.icon="fa-apple",n.name="Desktop - macOS";break;case e.deviceType.linuxDesktop:n.icon="fa-linux",n.name="Desktop - Linux";break;case e.deviceType.chrome:n.icon="fa-globe",n.name="Web Vault - Chrome";break;case e.deviceType.firefox:n.icon="fa-globe",n.name="Web Vault - Firefox";break;case e.deviceType.opera:n.icon="fa-globe",n.name="Web Vault - Opera";break;case e.deviceType.safari:n.icon="fa-globe",n.name="Web Vault - Safari";break;case e.deviceType.vivaldi:n.icon="fa-globe",n.name="Web Vault - Vivaldi";break;case e.deviceType.edge:n.icon="fa-globe",n.name="Web Vault - Edge";break;case e.deviceType.ie:n.icon="fa-globe",n.name="Web Vault - IE";break;case e.deviceType.unknown:n.icon="fa-globe",n.name="Web Vault - Unknown"}return n}(t);return{message:function(t,n){var s="";switch(t.Type){case e.eventType.User_LoggedIn:s="Logged in.";break;case e.eventType.User_ChangedPassword:s="Changed account password.";break;case e.eventType.User_Enabled2fa:s="Enabled two-step login.";break;case e.eventType.User_Disabled2fa:s="Disabled two-step login.";break;case e.eventType.User_Recovered2fa:s="Recovered account from two-step login.";break;case e.eventType.User_FailedLogIn:s="Login attempt failed with incorrect password.";break;case e.eventType.User_FailedLogIn2fa:s="Login attempt failed with incorrect two-step login.";break;case e.eventType.Cipher_Created:s=n.cipherInfo?"Created item "+r(t)+".":"Created.";break;case e.eventType.Cipher_Updated:s=n.cipherInfo?"Edited item "+r(t)+".":"Edited.";break;case e.eventType.Cipher_Deleted:s=n.cipherInfo?"Deleted item "+r(t)+".":"Deleted";break;case e.eventType.Cipher_AttachmentCreated:s=n.cipherInfo?"Created attachment for item "+r(t)+".":"Created attachment.";break;case e.eventType.Cipher_AttachmentDeleted:s=n.cipherInfo?"Deleted attachment for item "+r(t)+".":"Deleted attachment.";break;case e.eventType.Cipher_Shared:s=n.cipherInfo?"Shared item "+r(t)+".":"Shared.";break;case e.eventType.Cipher_UpdatedCollections:s=n.cipherInfo?"Update collections for item "+r(t)+".":"Updated collections.";break;case e.eventType.Collection_Created:s="Created collection "+a(t)+".";break;case e.eventType.Collection_Updated:s="Edited collection "+a(t)+".";break;case e.eventType.Collection_Deleted:s="Deleted collection "+a(t)+".";break;case e.eventType.Group_Created:s="Created group "+o(t)+".";break;case e.eventType.Group_Updated:s="Edited group "+o(t)+".";break;case e.eventType.Group_Deleted:s="Deleted group "+o(t)+".";break;case e.eventType.OrganizationUser_Invited:s="Invited user "+i(t)+".";break;case e.eventType.OrganizationUser_Confirmed:s="Confirmed user "+i(t)+".";break;case e.eventType.OrganizationUser_Updated:s="Edited user "+i(t)+".";break;case e.eventType.OrganizationUser_Removed:s="Removed user "+i(t)+".";break;case e.eventType.OrganizationUser_UpdatedGroups:s="Edited groups for user "+i(t)+".";break;case e.eventType.Organization_Updated:s="Edited organization settings."}return""===s?null:s}(t,n),appIcon:s.icon,appName:s.name}},n}]),angular.module("bit.services").factory("importService",["constants",function(e){var t={};t.import=function(t,i,m,g){var f,h,v,y,b,w,C,S,k,T,P,I,E,z,O,A,U,x,D,F,M,N,B,K,G,L,_,R,H,V,j,q,Y;if(i)switch(t){case"bitwardencsv":q=i,Y=m,Papa.parse(q,{header:!0,encoding:"UTF-8",complete:function(t){c(t);var n=[],r=[],o=[],a=0;angular.forEach(t.data,function(t,i){var c=n.length,u=r.length,d=t.folder&&""!==t.folder,p=d;if(d)for(a=0;a<n.length;a++)if(n[a].name===t.folder){p=!1,c=a;break}var m={favorite:!(!t.favorite||""===t.favorite||"0"===t.favorite),notes:t.notes&&""!==t.notes?t.notes:null,name:t.name&&""!==t.name?t.name:"--",type:e.cipherType.login};if(t.fields&&""!==t.fields){var g=t.fields.split(/(?:\r\n|\r|\n)/);for(a=0;a<g.length;a++)if(g[a]&&""!==g[a]){var f=g[a].lastIndexOf(": ");if(-1!==f){m.fields||(m.fields=[]);var h={name:g[a].substr(0,f),value:null,type:e.fieldType.text};g[a].length>f+2&&(h.value=g[a].substr(f+2)),m.fields.push(h)}}}var v=t.type?t.type.toLowerCase():null;switch(v){case"login":case null:case void 0:m.type=e.cipherType.login;var y=t.login_totp||t.totp,b=l(t.login_uri||t.uri),w=t.login_username||t.username,C=t.login_password||t.password;m.login={totp:y&&""!==y?y:null,uris:s(b),username:w&&""!==w?w:null,password:C&&""!==C?C:null};break;case"note":m.type=e.cipherType.secureNote,m.secureNote={type:0}}if(r.push(m),p&&n.push({name:t.folder}),d){var S={key:u,value:c};o.push(S)}}),Y(n,r,o)}});break;case"lastpass":p(i,m,g,!1);break;case"safeincloudxml":!function(t,n,r){var o=[],a=[],i=[],l=[],c=0,u=0;d(t,function(t){var d=$(t).find("database");if(d.length){var p=d.find("> label");if(p.length)for(c=0;c<p.length;c++){var m=$(p[c]);l[m.attr("id")]=o.length,o.push({name:m.attr("name")})}var g=d.find("> card");if(g.length)for(c=0;c<g.length;c++){var f=$(g[c]);if("true"!==f.attr("template")){var h={favorite:!1,notes:"",name:f.attr("title"),fields:null};if(h.name&&""!==h.name||(h.name="--"),"note"===f.attr("type"))h.type=e.cipherType.secureNote,h.secureNote={type:0};else{h.type=e.cipherType.login,h.login={};var v=f.find("> field");for(u=0;u<v.length;u++){var y=$(v[u]),b=y.text(),w=y.attr("type"),C=y.attr("name");b&&""!==b&&("login"===w?h.login.username=b:"password"===w?h.login.password=b:"notes"===w?h.notes+=b+"\n":"weblogin"===w||"website"===w?h.login.uris=s(b):b.length>200?h.notes+=C+": "+b+"\n":(h.fields||(h.fields=[]),h.fields.push({name:C,value:b,type:e.fieldType.text})))}}var S=f.find("> notes");for(u=0;u<S.length;u++)h.notes+=$(S[u]).text()+"\n";if(""===h.notes&&(h.notes=null),a.push(h),(p=f.find("> label_id")).length){var k=$(p[0]).text(),T=l[k];null!==k&&""!==k&&null!==T&&i.push({key:a.length-1,value:T})}}}n(o,a,i)}else r()},r)}(i,m,g);break;case"keepass2xml":!function(t,n,r){var o=[],a=[],i=[];d(t,function(t){var l=$(t).find("Root");if(l.length){var c=l.find("> Group");c.length&&(!function t(n,r,l){var c=o.length;var u=l;r||(""!==u&&(u+=" > "),u+=n.find("> Name").text(),o.push({name:u}));var d=n.find("> Entry");if(d.length)for(var p=0;p<d.length;p++){for(var m=$(d[p]),g=a.length,f={favorite:!1,notes:null,name:null,type:e.cipherType.login,login:{uris:null,username:null,password:null},fields:null},h=m.find("> String"),v=0;v<h.length;v++){var y=$(h[v]),b=y.find("> Key").text(),w=y.find("> Value").text();if(""!==w)switch(b){case"URL":f.login.uris=s(w);break;case"UserName":f.login.username=w;break;case"Password":f.login.password=w;break;case"Title":f.name=w;break;case"Notes":f.notes=null===f.notes?w+"\n":f.notes+w+"\n";break;default:w.length>200||w.indexOf("\n")>-1?(f.notes||(f.notes=""),f.notes+=b+": "+w+"\n"):(f.fields||(f.fields=[]),f.fields.push({name:b,value:w,type:e.fieldType.text}))}}null===f.name&&(f.name="--"),a.push(f),r||i.push({key:g,value:c})}var C=n.find("> Group");if(C.length)for(var S=0;S<C.length;S++)t($(C[S]),!1,u)}($(c[0]),!0,""),n(o,a,i))}else r()},r)}(i,m,g);break;case"keepassxcsv":V=i,j=m,Papa.parse(V,{header:!0,encoding:"UTF-8",complete:function(t){c(t);var n=[],r=[],o=[];angular.forEach(t.data,function(t,a){t.Group=t.Group.startsWith("Root/")?t.Group.replace("Root/",""):t.Group;var i=t.Group&&""!==t.Group?t.Group.split("/").join(" > "):null,l=n.length,c=r.length,u=null!==i,d=u,p=0;if(u)for(p=0;p<n.length;p++)if(n[p].name===i){d=!1,l=p;break}var m={type:e.cipherType.login,favorite:!1,notes:t.Notes&&""!==t.Notes?t.Notes:null,name:t.Title&&""!==t.Title?t.Title:"--",login:{uris:s(t.URL),username:t.Username&&""!==t.Username?t.Username:null,password:t.Password&&""!==t.Password?t.Password:null}};if(t.Title&&r.push(m),d&&n.push({name:i}),u){var g={key:c,value:l};o.push(g)}}),j(n,r,o)}});break;case"padlockcsv":R=i,H=m,Papa.parse(R,{encoding:"UTF-8",complete:function(t){c(t);var n=[],r=[],o=[],a=[],i=0,l=0;for(i=0;i<t.data.length;i++){var u=t.data[i];if(0!==i){var d=n.length,p=r.length,m=u[1]&&""!==u[1],g=m;if(m)for(l=0;l<n.length;l++)if(n[l].name===u[1]){g=!1,d=l;break}var f={favorite:!1,type:e.cipherType.login,notes:null,name:u[0]&&""!==u[0]?u[0]:"--",login:{uris:null,username:u[2]&&""!==u[2]?u[2]:null,password:u[3]&&""!==u[3]?u[3]:null},fields:null};if(a.length)for(l=4;l<u.length;l++){var h=u[l];if(h&&""!==h){var v=a[l-4];"url"===v.toLowerCase()||"uri"===v.toLowerCase()?f.login.uris=s(h):(f.fields||(f.fields=[]),f.fields.push({name:v,value:h,type:e.fieldType.text}))}}r.push(f),g&&n.push({name:u[1]}),m&&o.push({key:p,value:d})}else for(l=4;l<u.length;l++)a.push(u[l])}H(n,r,o)}});break;case"1password1pif":!function(t,n,r){var o=[],a=[],i=0;function l(t,n,r,o,a){for(var i=0;i<t.length;i++){var s=t[i];if(s[o]&&""!==s[o]){var l=s[o].toString();if(n.type==e.cipherType.login&&!n.login.username&&s[r]&&"username"===s[r])n.login.username=l;else if(n.type==e.cipherType.login&&!n.login.password&&s[r]&&"password"===s[r])n.login.password=l;else if(n.type==e.cipherType.login&&!n.login.totp&&s[r]&&s[r].startsWith("TOTP_"))n.login.totp=l;else if(l){var c=s[a]||"no_name";l.indexOf("\\n")>-1||l.length>200?(null===n.notes?n.notes="":n.notes+="\n",n.notes+=c+": "+l.split("\\r\\n").join("\n").split("\\n").join("\n")):(n.fields||(n.fields=[]),n.fields.push({name:c,value:l,type:e.fieldType.text}))}}}}u(t,function(t){var r=t.split(/(?:\r\n|\r|\n)/);for(i=0;i<r.length;i++){var c=r[i];if(c.length&&"{"===c[0]){var u=JSON.parse(c),d={type:e.cipherType.login,favorite:!(!u.openContents||!u.openContents.faveIndex),notes:null,name:u.title&&""!==u.title?u.title:"--",fields:null};if("securenotes.SecureNote"===u.typeName?(d.type=e.cipherType.secureNote,d.secureNote={type:0}):(d.type=e.cipherType.login,d.login={uris:s(u.location),username:null,password:null,totp:null}),u.secureContents&&(u.secureContents.notesPlain&&""!==u.secureContents.notesPlain&&(d.notes=u.secureContents.notesPlain.split("\\r\\n").join("\n").split("\\n").join("\n")),u.secureContents.fields&&l(u.secureContents.fields,d,"designation","value","name"),u.secureContents.sections))for(var p=0;p<u.secureContents.sections.length;p++)u.secureContents.sections[p].fields&&l(u.secureContents.sections[p].fields,d,"n","v","t");a.push(d)}}n(o,a,[])},r)}(i,m,g);break;case"1password6wincsv":K=i,G=m,L=[],_=[],Papa.parse(K,{encoding:"UTF-8",header:!0,complete:function(t){c(t);for(var n=0;n<t.data.length;n++){var r=t.data[n];if(r.title){var o={type:e.cipherType.login,favorite:!1,notes:r.notesPlain&&""!==r.notesPlain?r.notesPlain:"",name:r.title&&""!==r.title?r.title:"--",login:{uris:null,username:null,password:null}};for(var a in r)if(r.hasOwnProperty(a)){if(null===r[a]||""===r[a])continue;if(o.login.password||"password"!==a)if(o.login.username||"username"!==a)if(o.login.uris||"urls"!==a)"ainfo"===a||"autosubmit"===a||"notesPlain"===a||"ps"===a||"scope"===a||"tags"===a||"title"===a||"uuid"===a||a.startsWith("section:")||(""!==o.notes&&(o.notes+="\n"),o.notes+=a+": "+r[a]);else{var i=r[a].split(/(?:\r\n|\r|\n)/);o.login.uris=s(i)}else o.login.username=r[a];else o.login.password=r[a]}""===o.notes&&(o.notes=null),_.push(o)}}G(L,_,[])}});break;case"chromecsv":case"vivaldicsv":case"operacsv":N=i,B=m,Papa.parse(N,{header:!0,encoding:"UTF-8",complete:function(t){c(t);var n=[];angular.forEach(t.data,function(t,r){n.push({type:e.cipherType.login,favorite:!1,notes:null,name:t.name&&""!==t.name?t.name:"--",login:{uris:s(t.url),username:t.username&&""!==t.username?t.username:null,password:t.password&&""!==t.password?t.password:null}})}),B([],n,[])}});break;case"firefoxpasswordexportercsvxml":!function(t,n,r){var o=[],a=[];function i(e){var t="--";try{if(e&&""!==e){var n=document.createElement("a");n.href=e,n.hostname&&(t=n.hostname)}}catch(e){}return t}{if(!t.type||"text/xml"!==t.type)return void r("Only .xml exports are supported.");d(t,function(t){for(var r=$(t).find("entry"),l=0;l<r.length;l++){var c=$(r[l]);if(c){var u=c.attr("host"),d=c.attr("user"),p=c.attr("password");a.push({type:e.cipherType.login,favorite:!1,notes:null,name:i(u),login:{uris:s(u),username:d&&""!==d?d:null,password:p&&""!==p?p:null}})}}n(o,a,[])},r)}}(i,m,g);break;case"upmcsv":F=i,M=m,Papa.parse(F,{encoding:"UTF-8",complete:function(t){c(t);var n=[];angular.forEach(t.data,function(t,r){5===t.length&&n.push({type:e.cipherType.login,favorite:!1,notes:t[4]&&""!==t[4]?t[4]:null,name:t[0]&&""!==t[0]?t[0]:"--",login:{uris:s(t[3]),username:t[1]&&""!==t[1]?t[1]:null,password:t[2]&&""!==t[2]?t[2]:null}})}),M([],n,[])}});break;case"keepercsv":x=i,D=m,Papa.parse(x,{encoding:"UTF-8",complete:function(t){c(t);var n=[],r=[],o=[];angular.forEach(t.data,function(t,a){if(t.length>=6){var i=n.length,l=r.length,c=t[0]&&""!==t[0],u=c,d=0;if(c)for(d=0;d<n.length;d++)if(n[d].name===t[0]){u=!1,i=d;break}var p={type:e.cipherType.login,favorite:!1,notes:t[5]&&""!==t[5]?t[5]:null,name:t[1]&&""!==t[1]?t[1]:"--",login:{uris:s(t[4]),username:t[2]&&""!==t[2]?t[2]:null,password:t[3]&&""!==t[3]?t[3]:null},fields:null};if(t.length>6)for(d=6;d<t.length;d+=2)t[d+1]&&t[d+1].length>200?(p.notes||(p.notes=""),p.notes+=t[d]+": "+t[d+1]+"\n"):(p.fields||(p.fields=[]),p.fields.push({name:t[d],value:t[d+1],type:e.fieldType.text}));if(r.push(p),u&&n.push({name:t[0]}),c){var m={key:l,value:i};o.push(m)}}}),D(n,r,o)}});break;case"passworddragonxml":!function(t,n,r){var o=[],a=[],i=[],l=0;d(t,function(t){var c=$(t).find("PasswordManager");if(c.length){var u=c.find("> record");if(u.length)for(var d=0;d<u.length;d++){var p=$(u[d]),m=p.find("> Account-Name"),g=m.length?$(m):null,f=p.find("> User-Id"),h=f.length?$(f):null,v=p.find("> Password"),y=v.length?$(v):null,b=p.find("> URL"),w=b.length?$(b):null,C=p.find("> Notes"),S=C.length?$(C):null,k=p.find("> Category"),T=k.length?$(k):null,P=T?T.text():null,I=o.length,E=a.length,z=P&&""!==P&&"Unfiled"!==P,O=z;if(z)for(l=0;l<o.length;l++)if(o[l].name===P){O=!1,I=l;break}var A={type:e.cipherType.login,favorite:!1,notes:S&&""!==S.text()?S.text():null,name:g&&""!==g.text()?g.text():"--",login:{uris:w?s(w.text()):null,username:h&&""!==h.text()?h.text():null,password:y&&""!==y.text()?y.text():null},fields:null},U="";for(l=1;l<=10;l++)U+="> Attribute-"+l,l<10&&(U+=", ");var x=p.find(U);if(x.length)for(l=0;l<x.length;l++){var D=$(x[l]),F=D.prop("tagName"),M=D.text();M&&""!==M&&"null"!==M&&(M.length>200?(A.notes||(A.notes=""),A.notes+=F+": "+M+"\n"):(A.fields||(A.fields=[]),A.fields.push({name:F,value:M,type:e.fieldType.text})))}if(a.push(A),O&&o.push({name:P}),z){var N={key:E,value:I};i.push(N)}}n(o,a,i)}else r()},r)}(i,m,g);break;case"enpasscsv":A=i,U=m,Papa.parse(A,{encoding:"UTF-8",complete:function(t){c(t);for(var n=[],r=0;r<t.data.length;r++){var o=t.data[r];if(!(o.length<2||0===r&&"Title"===o[0])){var a=o[o.length-1],i={type:e.cipherType.login,name:o[0],favorite:!1,notes:a&&""!==a?a:null,fields:null,login:{uris:null,password:null,username:null,totp:null}};if(o.length>2&&o.length%2==0)for(var l=0;l<o.length-2;l+=2){var u=o[l+2];if(u&&""!==u){var d=o[l+1],p=d.toLowerCase();"url"!==p||i.login.uris?"username"!==p&&"email"!==p||i.login.username?"password"!==p||i.login.password?"totp"!==p||i.login.totp?u.length>200?(i.notes||(i.notes=""),i.notes+=d+": "+u+"\n"):(i.fields||(i.fields=[]),i.fields.push({name:d,value:u,type:e.fieldType.text})):i.login.totp=u:i.login.password=u:i.login.username=u:i.login.uris=s(u)}}n.push(i)}}U([],n,[])}});break;case"pwsafexml":!function(t,n,r){var o=[],a=[],i=[],l=0;d(t,function(t){var c=$(t).find("passwordsafe");if(c.length){var u=c.attr("delimiter"),d=c.find("> entry");if(d.length)for(var p=0;p<d.length;p++){var m=$(d[p]),g=m.find("> title"),f=g.length?$(g):null,h=m.find("> username"),v=h.length?$(h):null,y=m.find("> email"),b=y.length?$(y):null,w=b?b.text():null,C=m.find("> password"),S=C.length?$(C):null,k=m.find("> url"),T=k.length?$(k):null,P=m.find("> notes"),I=P.length?$(P):null,E=I?I.text().split(u).join("\n"):null,z=m.find("> group"),O=z.length?$(z):null,A=O?O.text().split(".").join(" > "):null,U=o.length,x=a.length,D=A&&""!==A,F=D;if(D)for(l=0;l<o.length;l++)if(o[l].name===A){F=!1,U=l;break}var M={type:e.cipherType.login,favorite:!1,notes:I&&""!==E?E:null,name:f&&""!==f.text()?f.text():"--",login:{uris:T?s(T.text()):null,username:v&&""!==v.text()?v.text():null,password:S&&""!==S.text()?S.text():null}};if(!M.login.username&&w&&""!==w?M.login.username=w:w&&""!==w&&(M.notes=null===M.notes?"Email: "+w:M.notes+"\nEmail: "+w),a.push(M),F&&o.push({name:A}),D){var N={key:x,value:U};i.push(N)}}n(o,a,i)}else r()},r)}(i,m,g);break;case"dashlanecsv":z=i,O=m,Papa.parse(z,{encoding:"UTF-8",complete:function(t){c(t);for(var n=[],r=0;r<t.data.length;r++){var o=!1,a=t.data[r];if(a.length&&1!==a.length){var i={type:e.cipherType.login,name:a[0]&&""!==a[0]?a[0]:"--",favorite:!1,notes:null,login:{uris:null,password:null,username:null}};if(2===a.length)i.login.uris=s(a[1]);else if(3===a.length)i.login.uris=s(a[1]),i.login.username=a[2];else if(4===a.length)""===a[2]&&""===a[3]?(i.login.username=a[1],i.notes=a[2]+"\n"+a[3]):(i.login.username=a[2],i.notes=a[1]+"\n"+a[3]);else if(5===a.length)i.login.uris=s(a[1]),i.login.username=a[2],i.login.password=a[3],i.notes=a[4];else if(6===a.length)""===a[2]?(i.login.username=a[3],i.login.password=a[4],i.notes=a[5]):(i.login.username=a[2],i.login.password=a[3],i.notes=a[4]+"\n"+a[5]),i.login.uris=s(a[1]);else if(7===a.length)""===a[2]?(i.login.username=a[3],i.notes=a[4]+"\n"+a[6]):(i.login.username=a[2],i.notes=a[3]+"\n"+a[4]+"\n"+a[6]),i.login.uris=s(a[1]),i.login.password=a[5];else{i.notes="";for(var l=1;l<a.length;l++)if(i.notes=i.notes+a[l]+"\n","NO_TYPE"===a[l]){o=!0;break}}o||(""===i.login.username&&(i.login.username=null),""===i.login.password&&(i.login.password=null),""===i.notes&&(i.notes=null),n.push(i))}}O([],n,[])}});break;case"stickypasswordxml":!function(t,n,r){var o=[],a=[],i=[],l=0;function c(e,t,n){var r=e.find('> Groups > Group[ID="'+t+'"]');if(r.length){n&&""!==n&&(n=" > "+n),n=r.attr("Name")+n;var o=r.attr("ParentID");return c(e,o,n)}return n}d(t,function(t){var u=$(t).find("root > Database");if(u.length){var d=u.find("> Logins > Login");if(d.length)for(var p=0;p<d.length;p++){var m=$(d[p]),g=m.attr("Name"),f=m.attr("Password"),h=m.attr("ID"),v=null,y=null,b=null,w=null,C=null;if(h&&""!==h){var S=u.find('> Accounts > Account > LoginLinks > Login[SourceLoginID="'+h+'"]');if(S.length){var k=S.parent().parent();k.length&&(v=k.attr("Name"),y=k.attr("Link"),w=k.attr("ParentID"),(b=k.attr("Comments"))&&(b=b.split("/n").join("\n")))}}w&&""!==w&&(C=c(u,w,""));var T=o.length,P=a.length,I=C&&""!==C,E=I;if(I)for(l=0;l<o.length;l++)if(o[l].name===C){E=!1,T=l;break}var z={type:e.cipherType.login,favorite:!1,notes:b&&""!==b?b:null,name:v&&""!==v?v:"--",login:{uris:s(y),username:g&&""!==g?g:null,password:f&&""!==f?f:null}};if(a.push(z),E&&o.push({name:C}),I){var O={key:P,value:T};i.push(O)}}n(o,a,i)}else r()},r)}(i,m,g);break;case"msecurecsv":I=i,E=m,Papa.parse(I,{encoding:"UTF-8",complete:function(t){c(t);var n=[],r=[],o=[];angular.forEach(t.data,function(t,a){if(t.length>=3){var i=n.length,l=r.length,c=t[0]&&""!==t[0]&&"Unassigned"!==t[0],u=c,d=0;if(c)for(d=0;d<n.length;d++)if(n[d].name===t[0]){u=!1,i=d;break}var p={type:e.cipherType.login,favorite:!1,notes:"",name:t[2]&&""!==t[2]?t[2]:null,login:{uris:null,username:null,password:null}};if("Web Logins"===t[1])p.login.uris=s(t[4]),p.login.username=t[5]&&""!==t[5]?t[5]:null,p.login.password=t[6]&&""!==t[6]?t[6]:null,p.notes=t[3]&&""!==t[3]?t[3].split("\\n").join("\n"):null;else if(t.length>3)for(var m=3;m<t.length;m++)t[m]&&""!==t[m]&&(""!==p.notes&&(p.notes=p.notes+"\n"),p.notes=p.notes+t[m]);if(t[1]&&""!==t[1]&&"Web Logins"!==t[1]&&(p.name=t[1]+": "+p.name),""===p.notes&&(p.notes=null),r.push(p),u&&n.push({name:t[0]}),c){var g={key:l,value:i};o.push(g)}}}),E(n,r,o)}});break;case"truekeycsv":C=i,S=m,k=[],T=[],P=["kind","autologin","favorite","hexcolor","protectedwithpassword","subdomainonly","type","tk_export_version","note","title","document_content"],Papa.parse(C,{header:!0,encoding:"UTF-8",complete:function(t){c(t),angular.forEach(t.data,function(t,n){var r={type:e.cipherType.login,favorite:!(!t.favorite||"true"!==t.favorite.toLowerCase()),notes:t.memo&&""!==t.memo?t.memo:null,name:t.name&&""!==t.name?t.name:"--",login:{uris:s(t.url),username:t.login&&""!==t.login?t.login:null,password:t.password&&""!==t.password?t.password:null},fields:null};if("login"!==t.kind)for(var o in r.name=t.title&&""!==t.title?t.title:"--",r.notes=t.note&&""!==t.note?t.note:null,r.notes||(r.notes=t.document_content&&""!==t.document_content?t.document_content:null),t)t.hasOwnProperty(o)&&P.indexOf(o.toLowerCase())<0&&t[o]&&""!==t[o]&&(t[o].length>200?(r.notes||(r.notes=""),r.notes+=o+": "+t[o]+"\n"):(r.fields||(r.fields=[]),r.fields.push({name:o,value:t[o],type:e.fieldType.text})));T.push(r)}),S(k,T,[])}});break;case"clipperzhtml":!function(t,o,i){var l=[],c=[];u(t,function(t){var i=$(t).find("textarea"),u=i&&i.length?i.val():null,d=u?JSON.parse(u):null;if(d&&d.length)for(var p=0;p<d.length;p++){var m=d[p],g={type:e.cipherType.login,favorite:!1,notes:"",name:m.label&&""!==m.label?m.label.split(" ")[0]:"--",login:{uris:null,username:null,password:null},fields:null};if(m.data&&m.data.notes&&""!==m.data.notes&&(g.notes=m.data.notes.split("\\n").join("\n")),m.currentVersion&&m.currentVersion.fields)for(var f in m.currentVersion.fields)if(m.currentVersion.fields.hasOwnProperty(f)){var h=m.currentVersion.fields[f],v=h.actionType.toLowerCase();switch(v){case"password":g.login.password=h.value;break;case"email":case"username":case"user":case"name":g.login.username=h.value;break;case"url":g.login.uris=s(h.value);break;default:!g.login.username&&a(h.label,r)?g.login.username=h.value:!g.login.password&&a(h.label,n)?g.login.password=h.value:h.value.length>200?(g.notes||(g.notes=""),g.notes+=h.label+": "+h.value+"\n"):(g.fields||(g.fields=[]),g.fields.push({name:h.label,value:h.value,type:e.fieldType.text}))}}""===g.notes&&(g.notes=null),c.push(g)}o(l,c,[])},i)}(i,m,g);break;case"avirajson":!function(t,n,r){var o=[],a=[],i=0;u(t,function(t){var r=JSON.parse(t);if(r&&r.accounts)for(i=0;i<r.accounts.length;i++){var l=r.accounts[i],c={type:e.cipherType.login,favorite:l.is_favorite&&!0===l.is_favorite,notes:null,name:l.label&&""!==l.label?l.label:l.domain,login:{uris:s(l.domain),username:l.username&&""!==l.username?l.username:null,password:l.password&&""!==l.password?l.password:null}};l.email&&""!==l.email&&(c.login.username&&""!==c.login.username?c.notes=l.email:c.login.username=l.email),c.name&&""!==c.name||(c.name="--"),a.push(c)}n(o,a,[])},r)}(i,m,g);break;case"roboformhtml":!function(t,o,i){var l=[],c=[];u(t,function(t){var i=$(t.split("­").join("").split("<WBR>").join("")).find("table.nobr");if(i.length)for(var u=0;u<i.length;u++){var d=$(i[u]),p={type:e.cipherType.login,favorite:!1,notes:"",name:d.find("span.caption").text(),login:{uris:null,username:null,password:null},fields:null},m=d.find(".subcaption").text();m&&""!==m&&(p.login.uris=s(m));var g=[];if($.each(d.find("table td:not(.subcaption)"),function(e,t){$(t).find("br").replaceWith("\n");var n=$(t).text();""!==n&&g.push(n.split("\\n").join("\n"))}),g.length&&g.length%2==0)for(var f=0;f<g.length;f+=2){var h=g[f],v=g[f+1];!p.login.password&&a(h.replace(":",""),n)?p.login.password=v:!p.login.username&&a(h.replace(":",""),r)?p.login.username=v:v.length>200?(p.notes||(p.notes=""),p.notes+=h+": "+v+"\n"):(p.fields||(p.fields=[]),p.fields.push({name:h,value:v,type:e.fieldType.text}))}p.notes&&""!==p.notes||(p.notes=null),p.name&&""!==p.name||(p.name="--"),c.push(p)}o(l,c,[])},i)}(i,m,g);break;case"saferpasscsv":!function(t,n,r){var o=[],a=[];Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(t){c(t),angular.forEach(t.data,function(t,n){var r,o;a.push({type:e.cipherType.login,favorite:!1,notes:t.notes&&""!==t.notes?t.notes:null,name:t.url&&""!==t.url?(r=t.url,o=document.createElement("a"),o.href=r,o.hostname.startsWith("www.")?o.hostname.replace("www.",""):o.hostname):"--",login:{uris:s(t.url),username:t.username&&""!==t.username?t.username:null,password:t.password&&""!==t.password?t.password:null}})}),n(o,a,[])}})}(i,m);break;case"ascendocsv":b=i,w=m,Papa.parse(b,{encoding:"UTF-8",complete:function(t){c(t);for(var i=[],l=0;l<t.data.length;l++){var u=t.data[l];if(!(u.length<2)){var d=u[u.length-1],p={type:e.cipherType.login,name:u[0],favorite:!1,notes:d&&""!==d?d:null,login:{uris:null,password:null,username:null},fields:null};if(u.length>2&&u.length%2==0)for(var m=0;m<u.length-2;m+=2){var g=u[m+2],f=u[m+1];f&&""!==f&&g&&""!==g&&(f.toLowerCase(),!p.login.uris&&a(f,o)?p.login.uris=s(g):!p.login.username&&a(f,r)?p.login.username=g:!p.login.password&&a(f,n)?p.login.password=g:g.length>200?(p.notes||(p.notes=""),p.notes+=f+": "+g+"\n"):(p.fields||(p.fields=[]),p.fields.push({name:f,value:g,type:e.fieldType.text})))}i.push(p)}}w([],i,[])}});break;case"passwordbossjson":!function(t,n,r){var o=[],a=[],i=0;u(t,function(t){var r=JSON.parse(t);if(r&&r.length)for(i=0;i<r.length;i++){var l=r[i],c={type:e.cipherType.login,favorite:!1,notes:"",name:l.name&&""!==l.name?l.name:"--",login:{uris:s(l.login_url),username:null,password:null},fields:null};if(l.identifiers){for(var u in l.identifiers.notes&&""!==l.identifiers.notes&&(c.notes=l.identifiers.notes.split("\\r\\n").join("\n").split("\\n").join("\n")),l.identifiers)if(l.identifiers.hasOwnProperty(u)){var d=l.identifiers[u];if("notes"===u||""===d||null===d)continue;"username"===u?c.login.username=d:"password"===u?c.login.password=d:d.length>200?(c.notes||(c.notes=""),c.notes+=u+": "+d+"\n"):(c.fields||(c.fields=[]),c.fields.push({name:u,value:d,type:e.fieldType.text}))}""===c.notes&&(c.notes=null),a.push(c)}}n(o,a,[])},r)}(i,m,g);break;case"zohovaultcsv":!function(t,n,r){function o(t,n){if(t&&""!==t)for(var r=t.split(/(?:\r\n|\r|\n)/),o=0;o<r.length;o++){var a=r[o],i=a.indexOf(":");if(!(i<0)){var s=a.substring(0,i),l=a.length>i?a.substring(i+1):null;if(s&&""!==s&&l&&""!==l&&"SecretType"!==s){var c=s.toLowerCase();"user name"===c?n.login.username=l:"password"===c?n.login.password=l:l.length>200?(n.notes||(n.notes=""),n.notes+=s+": "+l+"\n"):(n.fields||(n.fields=[]),n.fields.push({name:s,value:l,type:e.fieldType.text}))}}}}Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(t){c(t);var r=[],a=[],i=[];angular.forEach(t.data,function(t,n){var l=t.ChamberName,c=r.length,u=a.length,d=l&&""!==l,p=d,m=0;if(d)for(m=0;m<r.length;m++)if(r[m].name===l){p=!1,c=m;break}var g={type:e.cipherType.login,favorite:!(!t.Favorite||"1"!==t.Favorite),notes:t.Notes&&""!==t.Notes?t.Notes:"",name:t["Secret Name"]&&""!==t["Secret Name"]?t["Secret Name"]:"--",login:{uris:s(t["Secret URL"]),username:null,password:null},fields:null};if(o(t.SecretData,g),o(t.CustomData,g),""===g.notes&&(g.notes=null),t["Secret Name"]&&a.push(g),p&&r.push({name:l}),d){var f={key:u,value:c};i.push(f)}}),n(r,a,i)}})}(i,m);break;case"splashidcsv":v=i,y=m,Papa.parse(v,{encoding:"UTF-8",complete:function(t){c(t);var n=[],r=[],o=[];function a(e,t,n){for(var r=e;r<t.length-3;r++)t[r]&&""!==t[r]&&(n.notes?""!==n.notes&&(n.notes+="\n"):n.notes="",n.notes+=t[r])}for(var i=1;i<t.data.length;i++)if(!(t.data[i].length<3)){var l=t.data[i],u=l[t.data.length-1],d=l[t.data.length-2],p=l[0],m=n.length,g=r.length,f=u&&""!==u&&"Unfiled"!==u,h=f,v=0;if(f)for(v=0;v<n.length;v++)if(n[v].name===u){h=!1,m=v;break}var b={type:e.cipherType.login,favorite:!1,notes:d,name:l[1]&&""!==l[1]?l[1]:"--",fields:null,login:{uris:null,username:null,password:null}};if("Web Logins"===p||"Servers"===p||"Email Accounts"===p?(b.login.uris=s(l[4]),b.login.username=l[2]&&""!==l[2]?l[2]:null,b.login.password=l[3]&&""!==l[3]?l[3]:null,a(5,l,b)):l.length>2&&a(2,l,b),b.name&&"--"!==b.name&&"Web Logins"!==p&&"Servers"!==p&&"Email Accounts"!==p&&(b.name=p+": "+b.name),""===b.notes&&(b.notes=null),r.push(b),h&&n.push({name:u}),f){var w={key:g,value:m};o.push(w)}}y(n,r,o)}});break;case"meldiumcsv":f=i,h=m,Papa.parse(f,{header:!0,encoding:"UTF-8",complete:function(t){c(t);for(var n=[],r=0;r<t.data.length;r++){var o=t.data[r],a={type:e.cipherType.login,name:o.DisplayName&&""!==o.DisplayName?o.DisplayName:"--",favorite:!1,notes:o.Notes&&""!==o.Notes?o.Notes:null,login:{uris:s(o.Url),password:o.Password&&""!==o.Password?o.Password:null,username:o.UserName&&""!==o.UserName?o.UserName:null}};n.push(a)}h([],n,[])}});break;case"passkeepcsv":!function(t,n,r){function o(e,t){var n=t[e]||t[" "+e];return n&&""!==n?n:null}Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(t){c(t);var r=[],a=[],i=[];angular.forEach(t.data,function(t,n){var l=r.length,c=a.length,u=!!o("category",t),d=u,p=0;if(u)for(p=0;p<r.length;p++)if(r[p].name===o("category",t)){d=!1,l=p;break}var m={type:e.cipherType.login,favorite:!1,notes:o("description",t)?o("description",t):null,name:o("title",t)?o("title",t):"--",login:{uris:o("site",t)?s(o("site",t)):null,username:o("username",t)?o("username",t):null,password:o("password",t)?o("password",t):null}};if(o("password2",t)&&(m.notes?m.notes+="\n":m.notes="",m.notes+="Password 2: "+o("password2",t)),a.push(m),d&&r.push({name:o("category",t)}),u){var g={key:c,value:l};i.push(g)}}),n(r,a,i)}})}(i,m);break;case"gnomejson":!function(t,n,r){var o=[],a=[],i=[],l=0;u(t,function(t){var r=JSON.parse(t),c=0,u=0;if(r&&Object.keys(r).length)for(var d in r)if(r.hasOwnProperty(d)&&r[d].length)for(c=o.length,o.push({name:d}),l=0;l<r[d].length;l++){var p=r[d][l];if(p.display_name&&0===p.display_name.indexOf("http")){u=a.length;var m={type:e.cipherType.login,favorite:!1,notes:"",name:p.display_name.replace("http://","").replace("https://",""),login:{uris:s(p.display_name),username:p.attributes.username_value&&""!==p.attributes.username_value?p.attributes.username_value:null,password:p.secret&&""!==p.secret?p.secret:null}};for(var g in m.name>30&&(m.name=m.name.substring(0,30)),p.attributes)p.attributes.hasOwnProperty(g)&&"username_value"!==g&&"xdg:schema"!==g&&(""!==m.notes&&(m.notes+="\n"),m.notes+=g+": "+p.attributes[g]);""===m.notes&&(m.notes=null),a.push(m),i.push({key:u,value:c})}}n(o,a,i)},r)}(i,m,g);break;default:g()}else g()},t.importOrg=function(t,n,r,o){var a,i;if(n)switch(t){case"bitwardencsv":a=n,i=r,Papa.parse(a,{header:!0,encoding:"UTF-8",complete:function(t){c(t);var n,r=[],o=[],a=[];angular.forEach(t.data,function(t,i){var c=o.length;if(t.collections&&""!==t.collections){var u=t.collections.split(",");for(n=0;n<u.length;n++){for(var d=!0,p=r.length,m=0;m<r.length;m++)if(r[m].name===u[n]){d=!1,p=m;break}d&&r.push({name:u[n]}),a.push({key:c,value:p})}}var g={favorite:!1,notes:t.notes&&""!==t.notes?t.notes:null,name:t.name&&""!==t.name?t.name:"--",type:e.cipherType.login};if(t.fields&&""!==t.fields){var f=t.fields.split(/(?:\r\n|\r|\n)/);for(n=0;n<f.length;n++)if(f[n]&&""!==f[n]){var h=f[n].lastIndexOf(": ");if(-1!==h){g.fields||(g.fields=[]);var v={name:f[n].substr(0,h),value:null,type:e.fieldType.text};f[n].length>h+2&&(v.value=f[n].substr(h+2)),g.fields.push(v)}}}var y=t.type?t.type.toLowerCase():null;switch(y){case"login":case null:case void 0:g.type=e.cipherType.login;var b=t.login_totp||t.totp,w=l(t.login_uri||t.uri),C=t.login_username||t.username,S=t.login_password||t.password;g.login={totp:b&&""!==b?b:null,uris:s(w),username:C&&""!==C?C:null,password:S&&""!==S?S:null};break;case"note":g.type=e.cipherType.secureNote,g.secureNote={type:0}}o.push(g)}),i(r,o,a)}});break;case"lastpass":p(n,r,o,!0);break;default:o()}else o()};var n=["password","pass word","passphrase","pass phrase","pass","code","code word","codeword","secret","secret word","personpwd","key","keyword","key word","keyphrase","key phrase","form_pw","wppassword","pin","pwd","pw","pword","passwd","p","serial","serial#","license key","reg #","passwort"],r=["user","name","user name","username","login name","email","e-mail","id","userid","user id","login","form_loginname","wpname","mail","loginid","login id","log","personlogin","first name","last name","card#","account #","member","member #","nom","benutzername"],o=["url","hyper link","hyperlink","link","host","hostname","host name","server","address","hyper ref","href","web","website","web site","site","web-site","uri","ort","adresse"];function a(e,t){if(!e||""===e)return!1;e=e.trim().toLowerCase();for(var n=0;n<t.length;n++)if(e===t[n])return!0;return!1}function i(e){return-1===(e=e.toLowerCase().trim()).indexOf("://")&&e.indexOf(".")>=0&&(e="http://"+e),e.length>1e3?e.substring(0,1e3):e}function s(e){if(!e)return null;if("string"==typeof e)return[{uri:i(e),match:null}];if(e.length){for(var t=[],n=0;n<e.length;n++)t.push({uri:i(e[n]),match:null});return t}return null}function l(e){if(!e||""===e)return null;var t=Papa.parse(e);return t&&t.data&&t.data.length&&t.data[0].length?t.data[0]:null}function c(e){if(e.errors&&e.errors.length)for(var t=0;t<e.errors.length;t++)console.warn("Error parsing row "+e.errors[t].row+": "+e.errors[t].message)}function u(e,t,n){if("string"==typeof e)t(e);else{var r=new FileReader;r.readAsText(e,"utf-8"),r.onload=function(e){t(e.target.result)},r.onerror=function(e){n()}}}function d(e,t,n){u(e,function(e){t($.parseXML(e))},n)}function p(t,n,r,o){if("string"!=typeof t&&t.type&&"text/html"===t.type){var a=new FileReader;a.readAsText(t,"utf-8"),a.onload=function(e){var t,n=$(e.target.result),o=n.find("pre");if(1===o.length)t=o.text().trim(),u(Papa.parse(t,{header:!0,encoding:"UTF-8"}).data);else{for(var a=!1,i=0;i<n.length;i++)if("pre"===n[i].tagName.toLowerCase()){a=!0,t=n[i].outerText.trim(),u(Papa.parse(t,{header:!0,encoding:"UTF-8"}).data);break}a||r()}},a.onerror=function(e){r()}}else Papa.parse(t,{header:!0,encoding:"UTF-8",complete:function(e){c(e),u(e.data)},beforeFirstChunk:function(e){return e.replace(/^\s+/,"")}});function i(e,t,n){for(var r={dataObj:{},notes:null},o=0;o<e.length;o++){var a=e[o].split(":");a.length<1||"NoteType"===a[0]||n.indexOf(a[0])>-1||!a[1]||""===a[1]||("Notes"===a[0]?r.notes?r.notes+="\n"+a[1]:r.notes=a[1]:t.hasOwnProperty(a[0])?r.dataObj[t[a[0]]]=a[1]:(r.notes?r.notes+="\n":r.notes="",r.notes+=a[0]+": "+a[1]))}return r}function l(e){var t={cardholderName:e.ccname&&""!==e.ccname?e.ccname:null,number:e.ccnum&&""!==e.ccnum?e.ccnum:null,brand:e.ccnum&&""!==e.ccnum?function(e){if(!e)return null;var t=new RegExp("^4");return null!=e.match(t)?"Visa":/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(e)?"Mastercard":(t=new RegExp("^3[47]"),null!=e.match(t)?"Amex":(t=new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)"),null!=e.match(t)?"Discover":(t=new RegExp("^36"),null!=e.match(t)?"Diners Club":(t=new RegExp("^30[0-5]"),null!=e.match(t)?"Diners Club":(t=new RegExp("^35(2[89]|[3-8][0-9])"),null!=e.match(t)?"JCB":(t=new RegExp("^(4026|417500|4508|4844|491(3|7))"),null!=e.match(t)?"Visa":null))))))}(e.ccnum):null,code:e.cccsc&&""!==e.cccsc?e.cccsc:null};if(e.ccexp&&""!==e.ccexp&&e.ccexp.indexOf("-")>-1){var n=e.ccexp.split("-");n.length>1&&(t.expYear=n[0],t.expMonth=n[1],2===t.expMonth.length&&"0"===t.expMonth[0]&&(t.expMonth=t.expMonth[1]))}return t}function u(t){var r=[],a=[],c=[],u=0;angular.forEach(t,function(t,n){var d,p=r.length,m=a.length,g=t.grouping&&""!==t.grouping&&"(none)"!==t.grouping,f=g;if(g)for(u=0;u<r.length;u++)if(r[u].name===t.grouping){f=!1,p=u;break}if(t.hasOwnProperty("profilename")&&t.hasOwnProperty("profilelanguage")?(d={favorite:!1,name:t.profilename&&""!==t.profilename?t.profilename:"--",type:e.cipherType.card},""===t.title&&""===t.firstname&&""===t.lastname&&""===t.address1&&""===t.phone&&""===t.username&&""===t.email||(d.type=e.cipherType.identity)):d={favorite:!o&&"1"===t.fav,name:t.name&&""!==t.name?t.name:"--",type:"http://sn"===t.url?e.cipherType.secureNote:e.cipherType.login},d.type===e.cipherType.login)d.login={uris:s(t.url),username:t.username&&""!==t.username?t.username:null,password:t.password&&""!==t.password?t.password:null},d.notes=t.extra&&""!==t.extra?t.extra:null;else if(d.type===e.cipherType.secureNote){var h=t.extra.split(/(?:\r\n|\r|\n)/),v=!1;if(h.length){var y=h[0].split(":");if(y.length>1&&"NoteType"===y[0]&&("Credit Card"===y[1]||"Address"===y[1])){var b=null;"Credit Card"===y[1]?(b=i(h,{Number:"number","Name on Card":"cardholderName","Security Code":"code"},[]),d.type=e.cipherType.card,d.card=b.dataObj):"Address"===y[1]&&(b=i(h,{Title:"title","First Name":"firstName","Last Name":"lastName","Middle Name":"middleName",Company:"company","Address 1":"address1","Address 2":"address2","Address 3":"address3","City / Town":"city",State:"state","Zip / Postal Code":"postalCode",Country:"country","Email Address":"email",Username:"username"},[]),d.type=e.cipherType.identity,d.identity=b.dataObj),v=!0,d.notes=b.notes}}v||(d.secureNote={type:0},d.notes=t.extra&&""!==t.extra?t.extra:null)}else if(d.type===e.cipherType.card)d.card=l(t),d.notes=t.notes&&""!==t.notes?t.notes:null;else if(d.type===e.cipherType.identity&&(d.identity={title:t.title&&""!==t.title?t.title:null,firstName:t.firstname&&""!==t.firstname?t.firstname:null,middleName:t.middlename&&""!==t.middlename?t.middlename:null,lastName:t.lastname&&""!==t.lastname?t.lastname:null,username:t.username&&""!==t.username?t.username:null,company:t.company&&""!==t.company?t.company:null,ssn:t.ssn&&""!==t.ssn?t.ssn:null,address1:t.address1&&""!==t.address1?t.address1:null,address2:t.address2&&""!==t.address2?t.address2:null,address3:t.address3&&""!==t.address3?t.address3:null,city:t.city&&""!==t.city?t.city:null,state:t.state&&""!==t.state?t.state:null,postalCode:t.zip&&""!==t.zip?t.zip:null,country:t.country&&""!==t.country?t.country:null,email:t.email&&""!==t.email?t.email:null,phone:t.phone&&""!==t.phone?t.phone:null},d.notes=t.notes&&""!==t.notes?t.notes:null,d.identity.title&&(d.identity.title=d.identity.title.charAt(0).toUpperCase()+d.identity.title.slice(1)),t.ccnum&&""!==t.ccnum)){var w=JSON.parse(JSON.stringify(d));w.identity=null,w.type=e.cipherType.card,w.card=l(t),a.push(w)}if(a.push(d),f&&r.push({name:t.grouping}),g){var C={key:m,value:p};c.push(C)}}),n(r,a,c)}}return t}]),angular.module("bit.services").factory("passwordService",function(){var e={};function t(e,n){var r=0,o=n-e,a=Math.ceil(Math.log2(o));if(a>53)throw new Exception("We cannot generate numbers larger than 53 bits.");var i=Math.ceil(a/8),s=Math.pow(2,a)-1,l=new Uint8Array(i);window.crypto.getRandomValues(l);for(var c=8*(i-1),u=0;u<i;u++)r+=l[u]*Math.pow(2,c),c-=8;return(r&=s)>=o?t(e,n):e+r}return e.generatePassword=function(e){var n=angular.extend({},{length:10,ambiguous:!1,number:!0,minNumber:1,uppercase:!0,minUppercase:1,lowercase:!0,minLowercase:1,special:!1,minSpecial:1},e);n.uppercase&&n.minUppercase<0&&(n.minUppercase=1),n.lowercase&&n.minLowercase<0&&(n.minLowercase=1),n.number&&n.minNumber<0&&(n.minNumber=1),n.special&&n.minSpecial<0&&(n.minSpecial=1),(!n.length||n.length<1)&&(n.length=10);var r=n.minUppercase+n.minLowercase+n.minNumber+n.minSpecial;n.length<r&&(n.length=r);var o=[];if(n.lowercase&&n.minLowercase>0)for(var a=0;a<n.minLowercase;a++)o.push("l");if(n.uppercase&&n.minUppercase>0)for(var i=0;i<n.minUppercase;i++)o.push("u");if(n.number&&n.minNumber>0)for(var s=0;s<n.minNumber;s++)o.push("n");if(n.special&&n.minSpecial>0)for(var l=0;l<n.minSpecial;l++)o.push("s");for(;o.length<n.length;)o.push("a");o.sort(function(){return 2*t(0,1)-1});var c="",u="abcdefghijkmnopqrstuvwxyz";n.ambiguous&&(u+="l"),n.lowercase&&(c+=u);var d="ABCDEFGHIJKLMNPQRSTUVWXYZ";n.ambiguous&&(d+="O"),n.uppercase&&(c+=d);var p="23456789";n.ambiguous&&(p+="01"),n.number&&(c+=p);var m="!@#$%^&*";n.special&&(c+=m);for(var g="",f=0;f<n.length;f++){var h;switch(o[f]){case"l":h=u;break;case"u":h=d;break;case"n":h=p;break;case"s":h=m;break;case"a":h=c}var v=t(0,h.length-1);g+=h.charAt(v)}return g},e}),angular.module("bit.services").factory("tokenService",["$sessionStorage","$localStorage","jwtHelper",function(e,t,n){var r={},o=null,a=null;return r.setToken=function(t){e.accessToken=t,o=t},r.getToken=function(){return o||(o=e.accessToken),o||null},r.clearToken=function(){o=null,delete e.accessToken},r.setRefreshToken=function(t){e.refreshToken=t,a=t},r.getRefreshToken=function(){return a||(a=e.refreshToken),a||null},r.clearRefreshToken=function(){a=null,delete e.refreshToken},r.setTwoFactorToken=function(e,n){t.twoFactor||(t.twoFactor={}),t.twoFactor[n]=e},r.getTwoFactorToken=function(e){return t.twoFactor?t.twoFactor[e]:null},r.clearTwoFactorToken=function(e){e?t.twoFactor&&t.twoFactor[e]&&delete t.twoFactor[e]:delete t.twoFactor},r.clearTokens=function(){r.clearToken(),r.clearRefreshToken()},r.tokenSecondsRemaining=function(e,t){var r=n.getTokenExpirationDate(e);if(t=t||0,null===r)return 0;var o=r.valueOf()-((new Date).valueOf()+1e3*t);return Math.round(o/1e3)},r.tokenNeedsRefresh=function(e,t){return t=t||5,r.tokenSecondsRemaining(e)<60*t},r}]),angular.module("bit.services").factory("utilsService",["constants",function(e){var t,n={};return n.getDeviceType=function(n){return t||(t=navigator.userAgent.indexOf(" Vivaldi/")>=0?e.deviceType.vivaldi:window.chrome&&window.chrome.webstore?e.deviceType.chrome:"undefined"!=typeof InstallTrigger?e.deviceType.firefox:window.opr&&opr.addons||window.opera||navigator.userAgent.indexOf(" OPR/")>=0?e.deviceType.firefox:/constructor/i.test(window.HTMLElement)||"[object SafariRemoteNotification]"===(!window.safari||"undefined"!=typeof safari&&safari.pushNotification).toString()?e.deviceType.opera:document.documentMode?e.deviceType.ie:window.StyleMedia?e.deviceType.edge:e.deviceType.unknown)},n}]),angular.module("bit.services").factory("validationService",function(){var e={addErrors:function(t,n){var r=n.data,o="An unexpected error has occurred.";if(t.$errors=[],r&&angular.isObject(r))if(r&&r.ErrorModel&&(r=r.ErrorModel),r.ValidationErrors){for(var a in r.ValidationErrors)if(r.ValidationErrors.hasOwnProperty(a))for(var i=0;i<r.ValidationErrors[a].length;i++)e.addError(t,a,r.ValidationErrors[a][i])}else r.Message?t.$errors.push(r.Message):t.$errors.push(o);else t.$errors.push(o)},addError:function(e,t,n,r){!r&&e.$errors||(e.$errors=[]);for(var o=!0,a=0;a<e.$errors.length;a++)if(e.$errors[a]===n){o=!1;break}o&&e.$errors.push(n),t&&""!==t&&e[t]&&e[t].$registerApiError&&e[t].$registerApiError()},parseErrors:function(e){var t=e.data,n="An unexpected error has occurred.",r=[];if(!t||!angular.isObject(t))return r.push(n),r;for(var o in t&&t.ErrorModel&&(t=t.ErrorModel),t.ValidationErrors||(t.Message?r.push(t.Message):r.push(n)),t.ValidationErrors)if(t.ValidationErrors.hasOwnProperty(o))for(var a=0;a<t.ValidationErrors[o].length;a++)r.push(t.ValidationErrors[o][a]);return r}};return e}),angular.module("bit.vault").controller("settingsAddEditEquivalentDomainController",["$scope","$uibModalInstance","$analytics","domainIndex","domains",function(e,t,n,r,o){n.eventTrack("settingsAddEditEquivalentDomainController",{category:"Modal"}),e.domains=o,e.index=r,e.submit=function(o){n.eventTrack((r?"Edited":"Added")+" Equivalent Domain"),t.close({domains:e.domains,index:r})},e.close=function(){t.dismiss("close")}}]),angular.module("bit.settings").controller("settingsBillingAdjustStorageController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,r,o,a,i){o.eventTrack("settingsBillingAdjustStorageController",{category:"Modal"}),e.add=i,e.storageAdjustment=0,e.submit=function(){var t={storageGbAdjustment:e.storageAdjustment};i||(t.storageGbAdjustment*=-1),e.submitPromise=r.accounts.putStorage(null,t).$promise.then(function(t){i?(o.eventTrack("Added Storage"),a.success("You have added "+e.storageAdjustment+" GB.")):(o.eventTrack("Removed Storage"),a.success("You have removed "+e.storageAdjustment+" GB.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("settingsBillingChangePaymentController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","existingPaymentMethod","appSettings","$timeout",function(e,t,n,r,o,a,i,s,l){o.eventTrack("settingsBillingChangePaymentController",{category:"Modal"}),e.existingPaymentMethod=i,e.paymentMethod="card",e.dropinLoaded=!1,e.showPaymentOptions=!1,e.hideBank=!0,e.card={};var c=null;e.changePaymentMethod=function(t){e.paymentMethod=t,"paypal"===e.paymentMethod&&braintree.dropin.create({authorization:s.braintreeKey,container:"#bt-dropin-container",paymentOptionPriority:["paypal"],paypal:{flow:"vault",buttonStyle:{label:"pay",size:"medium",shape:"pill",color:"blue"}}},function(t,n){t?console.error(t):(c=n,l(function(){e.dropinLoaded=!0}))})},e.submit=function(){var t;e.submitPromise=(t=e.card,"paypal"===e.paymentMethod?c.requestPaymentMethod().then(function(e){return e.nonce}).catch(function(e){throw e.message}):stripe.card.createToken(t).then(function(e){return e.id}).catch(function(e){throw e.message})).then(function(e){if(!e)throw"No payment token.";var t={paymentToken:e};return r.accounts.putPayment(null,t).$promise},function(e){throw e}).then(function(t){e.card=null,i?(o.eventTrack("Changed Payment Method"),a.success("You have changed your payment method.")):(o.eventTrack("Added Payment Method"),a.success("You have added a payment method.")),n.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsBillingController",["$scope","apiService","authService","$state","$uibModal","toastr","$analytics","appSettings",function(e,t,n,r,o,a,i,s){e.selfHosted=s.selfHosted,e.charges=[],e.paymentSource=null,e.subscription=null,e.loading=!0;var l=null;function c(){n.getUserProfile().then(function(n){return e.premium=n.premium,n.premium?t.accounts.getBilling({}).$promise:null}).then(function(t){if(!t)return r.go("backend.user.settingsPremium");var n=0;if(e.expiration=t.Expiration,l=t.License,e.storage=null,t&&t.MaxStorageGb&&(e.storage={currentGb:t.StorageGb||0,maxGb:t.MaxStorageGb,currentName:t.StorageName||"0 GB"},e.storage.percentage=+(e.storage.currentGb/e.storage.maxGb*100).toFixed(2)),e.subscription=null,t&&t.Subscription&&(e.subscription={trialEndDate:t.Subscription.TrialEndDate,cancelledDate:t.Subscription.CancelledDate,status:t.Subscription.Status,cancelled:t.Subscription.Cancelled,markedForCancel:!t.Subscription.Cancelled&&t.Subscription.CancelAtEndDate}),e.nextInvoice=null,t&&t.UpcomingInvoice&&(e.nextInvoice={date:t.UpcomingInvoice.Date,amount:t.UpcomingInvoice.Amount}),t&&t.Subscription&&t.Subscription.Items)for(e.subscription.items=[],n=0;n<t.Subscription.Items.length;n++)e.subscription.items.push({amount:t.Subscription.Items[n].Amount,name:t.Subscription.Items[n].Name,interval:t.Subscription.Items[n].Interval,qty:t.Subscription.Items[n].Quantity});e.paymentSource=null,t&&t.PaymentSource&&(e.paymentSource={type:t.PaymentSource.Type,description:t.PaymentSource.Description,cardBrand:t.PaymentSource.CardBrand});var o=[];if(t&&t.Charges)for(n=0;n<t.Charges.length;n++)o.push({date:t.Charges[n].CreatedDate,paymentSource:t.Charges[n].PaymentSource?t.Charges[n].PaymentSource.Description:"-",amount:t.Charges[n].Amount,status:t.Charges[n].Status,failureMessage:t.Charges[n].FailureMessage,refunded:t.Charges[n].Refunded,partiallyRefunded:t.Charges[n].PartiallyRefunded,refundedAmount:t.Charges[n].RefundedAmount,invoiceId:t.Charges[n].InvoiceId});e.charges=o,e.loading=!1})}e.expiration=null,e.$on("$viewContentLoaded",function(){c()}),e.changePayment=function(){e.selfHosted||o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingChangePayment.html",controller:"settingsBillingChangePaymentController",resolve:{existingPaymentMethod:function(){return e.paymentSource?e.paymentSource.description:null}}}).result.then(function(){c()})},e.adjustStorage=function(t){e.selfHosted||o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingAdjustStorage.html",controller:"settingsBillingAdjustStorageController",resolve:{add:function(){return t}}}).result.then(function(){c()})},e.cancel=function(){e.selfHosted||confirm("Are you sure you want to cancel? You will lose access to all premium features at the end of this billing cycle.")&&t.accounts.putCancelPremium({},{}).$promise.then(function(e){i.eventTrack("Canceled Premium"),a.success("Premium subscription has been canceled."),c()})},e.reinstate=function(){e.selfHosted||confirm("Are you sure you want to remove the cancellation request and reinstate your premium membership?")&&t.accounts.putReinstatePremium({},{}).$promise.then(function(e){i.eventTrack("Reinstated Premium"),a.success("Premium cancellation request has been removed."),c()})},e.updateLicense=function(){e.selfHosted&&o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingUpdateLicense.html",controller:"settingsBillingUpdateLicenseController"}).result.then(function(){c()})},e.license=function(){if(!e.selfHosted){var t=JSON.stringify(l,null,2),n=new Blob([t]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(n,"bitwarden_premium_license.json");else{var r=window.document.createElement("a");r.href=window.URL.createObjectURL(n,{type:"text/plain"}),r.download="bitwarden_premium_license.json",document.body.appendChild(r),r.click(),document.body.removeChild(r)}}}}]),angular.module("bit.settings").controller("settingsBillingUpdateLicenseController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","validationService",function(e,t,n,r,o,a,i){o.eventTrack("settingsBillingUpdateLicenseController",{category:"Modal"}),e.submit=function(t){var s=document.getElementById("file").files;if(s&&s.length){var l=new FormData;l.append("license",s[0]),e.submitPromise=r.accounts.putLicense(l).$promise.then(function(e){o.eventTrack("Updated License"),a.success("You have updated your license."),n.close()})}else i.addError(t,"file","Select a license file.",!0)},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsChangeEmailController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","validationService",function(e,t,n,r,o,a,i,s,l){var c,u,d;s.eventTrack("settingsChangeEmailController",{category:"Modal"}),e.token=function(t,r){o.getEncKey()?(u=t.masterPassword,d=t.newEmail.toLowerCase(),e.tokenPromise=o.hashPassword(u).then(function(t){var r={newEmail:d,masterPasswordHash:c=t};return n.accounts.emailToken(r,function(){e.tokenSent=!0}).$promise})):l.addError(r,null,"You cannot change your email until you update your encryption key.",!0)},e.confirm=function(l){e.confirmPromise=o.makeKeyAndHash(d,u).then(function(e){var t=o.getEncKey(),r=o.encrypt(t.key,e.key,"raw"),a={token:l.token,newEmail:d,masterPasswordHash:c,newMasterPasswordHash:e.hash,key:r};return n.accounts.email(a).$promise}).then(function(){return r.dismiss("cancel"),a.logOut(),s.eventTrack("Changed Email"),t.go("frontend.login.info")}).then(function(){i.success("Please log back in.","Email Changed")})},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsChangePasswordController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","validationService","toastr","$analytics",function(e,t,n,r,o,a,i,s,l){l.eventTrack("settingsChangePasswordController",{category:"Modal"}),e.save=function(c,u){var d,p=!1;(o.getEncKey()||(i.addError(u,null,"You cannot change your master password until you update your encryption key.",!0),p=!0),e.model.newMasterPassword.length<8&&(i.addError(u,"NewMasterPasswordHash","Master password must be at least 8 characters long.",!0),p=!0),e.model.newMasterPassword!==e.model.confirmNewMasterPassword&&(i.addError(u,"ConfirmNewMasterPasswordHash","New master password confirmation does not match.",!0),p=!0),p)||(e.savePromise=a.getUserProfile().then(function(e){return o.makeKeyAndHash(e.email,c.newMasterPassword)}).then(function(e){return d=e,o.hashPassword(c.masterPassword)}).then(function(e){var t=o.getEncKey(),r=o.encrypt(t.key,d.key,"raw"),a={masterPasswordHash:e,newMasterPasswordHash:d.hash,key:r};return n.accounts.putPassword(a).$promise}).then(function(){return r.dismiss("cancel"),a.logOut(),l.eventTrack("Changed Password"),t.go("frontend.login.info")}).then(function(){s.success("Please log back in.","Master Password Changed")}))},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsController",["$scope","$state","$uibModal","apiService","toastr","authService","$localStorage","$rootScope","cipherService",function(e,t,n,r,o,a,i,s,l){function c(){$("html, body").animate({scrollTop:0},200)}e.model={profile:{},email:null,disableWebsiteIcons:!1},e.$on("$viewContentLoaded",function(){r.accounts.getProfile({},function(t){if(e.model={profile:{name:t.Name,masterPasswordHint:t.MasterPasswordHint,culture:t.Culture},email:t.Email,disableWebsiteIcons:i.disableWebsiteIcons},t.Organizations){for(var n=[],r=0;r<t.Organizations.length;r++)2===t.Organizations[r].Status&&n.push({id:t.Organizations[r].Id,name:t.Organizations[r].Name,status:t.Organizations[r].Status,type:t.Organizations[r].Type,enabled:t.Organizations[r].Enabled});e.model.organizations=n}})}),e.generalSave=function(){e.generalPromise=r.accounts.putProfile({},e.model.profile,function(e){a.setUserProfile(e).then(function(e){o.success("Account has been updated.","Success!")})}).$promise},e.passwordHintSave=function(){e.passwordHintPromise=r.accounts.putProfile({},e.model.profile,function(e){a.setUserProfile(e).then(function(e){o.success("Account has been updated.","Success!")})}).$promise},e.optionsSave=function(){i.disableWebsiteIcons=l.disableWebsiteIcons=e.model.disableWebsiteIcons,s.vaultCiphers=null,o.success("Options have been updated.","Success!")},e.changePassword=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsChangePassword.html",controller:"settingsChangePasswordController"})},e.changeEmail=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsChangeEmail.html",controller:"settingsChangeEmailController"})},e.viewOrganization=function(e){if(2===e.type)return c(),void o.error("You cannot manage this organization.");t.go("backend.org.dashboard",{orgId:e.id})},e.leaveOrganization=function(t){confirm("Are you sure you want to leave this organization ("+t.name+")?")&&r.organizations.postLeave({id:t.id},{},function(n){a.refreshAccessToken().then(function(){var n=e.model.organizations.indexOf(t);n>-1&&e.model.organizations.splice(n,1),o.success("You have left the organization."),c()})},function(e){o.error("Unable to leave this organization."),c()})},e.sessions=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsSessions.html",controller:"settingsSessionsController"})},e.delete=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsDelete.html",controller:"settingsDeleteController"})},e.purge=function(){n.open({animation:!0,templateUrl:"app/settings/views/settingsPurge.html",controller:"settingsPurgeController"})}}]),angular.module("bit.settings").controller("settingsCreateOrganizationController",["$scope","$state","apiService","cryptoService","toastr","$analytics","authService","constants","appSettings","validationService",function(e,t,n,r,o,a,i,s,l,c){e.plans=s.plans,e.storageGb=s.storageGb,e.paymentMethod="card",e.selfHosted=l.selfHosted,e.model={plan:"free",additionalSeats:0,interval:"year",ownedBusiness:!1,additionalStorageGb:null},e.totalPrice=function(){return"month"===e.model.interval?(e.model.additionalSeats||0)*(e.plans[e.model.plan].monthlySeatPrice||0)+(e.model.additionalStorageGb||0)*e.storageGb.monthlyPrice+(e.plans[e.model.plan].monthlyBasePrice||0):(e.model.additionalSeats||0)*(e.plans[e.model.plan].annualSeatPrice||0)+(e.model.additionalStorageGb||0)*e.storageGb.yearlyPrice+(e.plans[e.model.plan].annualBasePrice||0)},e.changePaymentMethod=function(t){e.paymentMethod=t},e.changedPlan=function(){e.plans[e.model.plan].hasOwnProperty("monthPlanType")&&(e.model.interval="year"),e.plans[e.model.plan].noAdditionalSeats?e.model.additionalSeats=0:e.model.additionalSeats||e.plans[e.model.plan].baseSeats||e.plans[e.model.plan].noAdditionalSeats||(e.model.additionalSeats=1)},e.changedBusiness=function(){e.model.ownedBusiness&&(e.model.plan="teams")},e.submit=function(s,l){var u=r.makeShareKey(),d=r.encrypt("Default Collection",u.key);if(e.selfHosted){var p=document.getElementById("file").files;if(!p||!p.length)return void c.addError(l,"file","Select a license file.",!0);var m=new FormData;m.append("license",p[0]),m.append("key",u.ct),m.append("collectionName",d),e.submitPromise=n.organizations.postLicense(m).$promise.then(h)}else if("free"===s.plan){var g={name:s.name,planType:s.plan,key:u.ct,billingEmail:s.billingEmail,collectionName:d};e.submitPromise=n.organizations.post(g).$promise.then(h)}else{var f=null;if("card"===e.paymentMethod)f=stripe.card.createToken(s.card);else{if("bank"!==e.paymentMethod)return;s.bank.currency="USD",s.bank.country="US",f=stripe.bankAccount.createToken(s.bank)}e.submitPromise=f.then(function(t){var r={name:s.name,planType:"month"===s.interval?e.plans[s.plan].monthPlanType:e.plans[s.plan].annualPlanType,key:u.ct,paymentToken:t.id,additionalSeats:s.additionalSeats,additionalStorageGb:s.additionalStorageGb,billingEmail:s.billingEmail,businessName:s.ownedBusiness?s.businessName:null,country:"card"===e.paymentMethod?s.card.address_country:null,collectionName:d};return n.organizations.post(r).$promise},function(e){throw e.message}).then(h)}function h(e){a.eventTrack("Created Organization"),i.addProfileOrganizationOwner(e,u.ct),i.refreshAccessToken().then(function(){v(e.Id)},function(){v(e.Id)})}function v(e){t.go("backend.org.dashboard",{orgId:e}).then(function(){o.success("Your new organization is ready to go!","Organization Created")})}}}]),angular.module("bit.settings").controller("settingsDeleteController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","tokenService",function(e,t,n,r,o,a,i,s,l){s.eventTrack("settingsDeleteController",{category:"Modal"}),e.submit=function(c){var u;e.submitPromise=a.getUserProfile().then(function(e){return u=e,o.hashPassword(c.masterPassword)}).then(function(e){return n.accounts.postDelete({masterPasswordHash:e}).$promise}).then(function(){return r.dismiss("cancel"),a.logOut(),l.clearTwoFactorToken(u.email),s.eventTrack("Deleted Account"),t.go("frontend.login.info")}).then(function(){i.success("Your account has been closed and all associated data has been deleted.","Account Deleted")})},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsDomainsController",["$scope","$state","apiService","toastr","$analytics","$uibModal",function(e,t,n,r,o,a){e.globalEquivalentDomains=[],e.equivalentDomains=[],n.settings.getDomains({},function(t){var n;if(t.EquivalentDomains)for(n=0;n<t.EquivalentDomains.length;n++)e.equivalentDomains.push(t.EquivalentDomains[n].join(", "));if(t.GlobalEquivalentDomains)for(n=0;n<t.GlobalEquivalentDomains.length;n++)e.globalEquivalentDomains.push({domains:t.GlobalEquivalentDomains[n].Domains.join(", "),excluded:t.GlobalEquivalentDomains[n].Excluded,key:t.GlobalEquivalentDomains[n].Type})}),e.toggleExclude=function(e){e.excluded=!e.excluded},e.customize=function(t){t.excluded=!0,e.equivalentDomains.push(t.domains)},e.delete=function(t){e.equivalentDomains.splice(t,1),e.$emit("removeAppendedDropdownMenu")},e.addEdit=function(t){a.open({animation:!0,templateUrl:"app/settings/views/settingsAddEditEquivalentDomain.html",controller:"settingsAddEditEquivalentDomainController",resolve:{domainIndex:function(){return t},domains:function(){return null!==t?e.equivalentDomains[t]:null}}}).result.then(function(t){t.domains&&(t.domains=t.domains.split(" ").join("").split(",").join(", ")),null!==t.index?e.equivalentDomains[t.index]=t.domains:e.equivalentDomains.push(t.domains)})},e.saveGlobal=function(){e.globalPromise=i()},e.saveCustom=function(){e.customPromise=i()};var i=function(){for(var t={ExcludedGlobalEquivalentDomains:[],EquivalentDomains:[]},a=0;a<e.globalEquivalentDomains.length;a++)e.globalEquivalentDomains[a].excluded&&t.ExcludedGlobalEquivalentDomains.push(e.globalEquivalentDomains[a].key);for(a=0;a<e.equivalentDomains.length;a++)t.EquivalentDomains.push(e.equivalentDomains[a].split(" ").join("").split(","));return t.EquivalentDomains.length||(t.EquivalentDomains=null),t.ExcludedGlobalEquivalentDomains.length||(t.ExcludedGlobalEquivalentDomains=null),n.settings.putDomains(t,function(e){o.eventTrack("Saved Equivalent Domains"),r.success("Domains have been updated.","Success!")}).$promise}}]),angular.module("bit.settings").controller("settingsPremiumController",["$scope","$state","apiService","toastr","$analytics","authService","constants","$timeout","appSettings","validationService",function(e,t,n,r,o,a,i,s,l,c){var u=null;a.getUserProfile().then(function(e){if((u=e)&&u.premium)return t.go("backend.user.settingsBilling")}),e.selfHosted=l.selfHosted;var d=null;function p(){return a.updateProfilePremium(!0).then(function(){return o.eventTrack("Signed Up Premium"),a.refreshAccessToken()}).then(function(){return t.go("backend.user.settingsBilling")}).then(function(){r.success("Premium upgrade complete.","Success")})}e.storageGbPrice=i.storageGb.yearlyPrice,e.premiumPrice=i.premium.price,e.paymentMethod="card",e.dropinLoaded=!1,e.model={additionalStorageGb:null},e.changePaymentMethod=function(t){e.paymentMethod=t,"paypal"===e.paymentMethod&&braintree.dropin.create({authorization:l.braintreeKey,container:"#bt-dropin-container",paymentOptionPriority:["paypal"],paypal:{flow:"vault",buttonStyle:{label:"pay",size:"medium",shape:"pill",color:"blue"}}},function(t,n){t?console.error(t):(d=n,s(function(){e.dropinLoaded=!0}))})},e.totalPrice=function(){return e.premiumPrice+(e.model.additionalStorageGb||0)*e.storageGbPrice},e.submit=function(t,r){if(e.selfHosted){if(u&&!u.emailVerified)return void c.addError(r,null,"Your account's email address first must be verified.",!0);var o=document.getElementById("file").files;if(!o||!o.length)return void c.addError(r,"file","Select a license file.",!0);var a=new FormData;a.append("license",o[0]),e.submitPromise=n.accounts.postPremium(a).$promise.then(function(e){return p()})}else e.submitPromise=(i=t,"paypal"===e.paymentMethod?d.requestPaymentMethod().then(function(e){return e.nonce}).catch(function(e){throw e.message}):stripe.card.createToken(i.card).then(function(e){return e.id}).catch(function(e){throw e.message})).then(function(e){if(!e)throw"No payment token.";var r=new FormData;return r.append("paymentToken",e),r.append("additionalStorageGb",t.additionalStorageGb||0),n.accounts.postPremium(r).$promise},function(e){throw e}).then(function(e){return p()});var i}}]),angular.module("bit.settings").controller("settingsPurgeController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","tokenService",function(e,t,n,r,o,a,i,s,l){s.eventTrack("settingsPurgeController",{category:"Modal"}),e.submit=function(a){e.submitPromise=o.hashPassword(a.masterPassword).then(function(e){return n.ciphers.purge({masterPasswordHash:e}).$promise}).then(function(){return r.dismiss("cancel"),s.eventTrack("Purged Vault"),t.go("backend.user.vault",{refreshFromServer:!0})}).then(function(){i.success("All items in your vault have been deleted.","Vault Purged")})},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsSessionsController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","tokenService","toastr","$analytics",function(e,t,n,r,o,a,i,s,l){l.eventTrack("settingsSessionsController",{category:"Modal"}),e.submit=function(c){var u,d;e.submitPromise=o.hashPassword(c.masterPassword).then(function(e){return u=e,a.getUserProfile()}).then(function(e){return d=e,n.accounts.putSecurityStamp({masterPasswordHash:u}).$promise}).then(function(){return r.dismiss("cancel"),a.logOut(),i.clearTwoFactorToken(d.email),l.eventTrack("Deauthorized Sessions"),t.go("frontend.login.info")}).then(function(){s.success("Please log back in.","All Sessions Deauthorized")})},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsTwoStepAuthenticatorController",["$scope","apiService","$uibModalInstance","cryptoService","authService","$q","toastr","$analytics","constants","$timeout",function(e,t,n,r,o,a,i,s,l,c){s.eventTrack("settingsTwoStepAuthenticatorController",{category:"Modal"});var u,d="Bitwarden",p=null,m=null;function g(t){var n;e.enabled=t.Enabled,m=t.Key,e.model={key:(n=m,n?n.replace(/(.{4})/g,"$1 ").trim().toUpperCase():null),qr:"https://chart.googleapis.com/chart?chs=160x160&chld=L|0&cht=qr&chl=otpauth://totp/"+d+":"+encodeURIComponent(p.email)+"%3Fsecret="+encodeURIComponent(m)+"%26issuer="+d},e.updateModel={token:null}}c(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=r.hashPassword(n.masterPassword).then(function(e){return u=e,t.twoFactor.getAuthenticator({},{masterPasswordHash:u}).$promise}).then(function(e){return a=e,o.getUserProfile()}).then(function(t){p=t,e.account=p.email,g(a)})},e.submit=function(n){var r;n&&n.token?(r=n,e.submitPromise=t.twoFactor.putAuthenticator({},{token:r.token.replace(" ",""),key:m,masterPasswordHash:u},function(e){s.eventTrack("Enabled Two-step Authenticator"),g(e),r.token=null}).$promise):function(){if(!confirm("Are you sure you want to disable the authenticator app provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:u,type:l.twoFactorProvider.authenticator},function(t){s.eventTrack("Disabled Two-step Authenticator"),i.success("Authenticator app has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}()};var f=!1;e.close=function(){f=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,r){f||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepController",["$scope","apiService","toastr","$analytics","constants","$filter","$uibModal","authService",function(e,t,n,r,o,a,i,s){e.providers=o.twoFactorProviderInfo,e.premium=!0,s.getUserProfile().then(function(n){return e.premium=n.premium,t.twoFactor.list({}).$promise}).then(function(t){if(t.Data)for(var n=0;n<t.Data.length;n++)if(t.Data[n].Enabled){var r=a("filter")(e.providers,{type:t.Data[n].Type});r.length&&(r[0].enabled=!0)}}),e.edit=function(t){if(e.premium||t.free){if(t.type===o.twoFactorProvider.authenticator)typeName="Authenticator";else if(t.type===o.twoFactorProvider.email)typeName="Email";else if(t.type===o.twoFactorProvider.yubikey)typeName="Yubi";else if(t.type===o.twoFactorProvider.duo)typeName="Duo";else{if(t.type!==o.twoFactorProvider.u2f)return;typeName="U2f"}i.open({animation:!0,templateUrl:"app/settings/views/settingsTwoStep"+typeName+".html",controller:"settingsTwoStep"+typeName+"Controller",resolve:{enabled:function(){return t.enabled}}}).result.then(function(e){(e||!1===e)&&(t.enabled=e)})}else i.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})},e.viewRecover=function(){i.open({animation:!0,templateUrl:"app/settings/views/settingsTwoStepRecover.html",controller:"settingsTwoStepRecoverController"})}}]),angular.module("bit.settings").controller("settingsTwoStepDuoController",["$scope","apiService","$uibModalInstance","cryptoService","toastr","$analytics","constants","$timeout",function(e,t,n,r,o,a,i,s){var l;function c(t){e.enabled=t.Enabled,e.updateModel={ikey:t.IntegrationKey,skey:t.SecretKey,host:t.Host}}a.eventTrack("settingsTwoStepDuoController",{category:"Modal"}),e.updateModel={token:null,host:null,ikey:null,skey:null},s(function(){$("#masterPassword").focus()}),e.auth=function(n){e.authPromise=r.hashPassword(n.masterPassword).then(function(e){return l=e,t.twoFactor.getDuo({},{masterPasswordHash:l}).$promise}).then(function(t){c(t),e.authed=!0})},e.submit=function(n){var r;e.enabled?function(){if(!confirm("Are you sure you want to disable the Duo provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:l,type:i.twoFactorProvider.duo},function(t){a.eventTrack("Disabled Two-step Duo"),o.success("Duo has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}():(r=n,e.submitPromise=t.twoFactor.putDuo({},{integrationKey:r.ikey,secretKey:r.skey,host:r.host,masterPasswordHash:l},function(e){a.eventTrack("Enabled Two-step Duo"),c(e)}).$promise)};var u=!1;e.close=function(){u=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,r){u||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepEmailController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout",function(e,t,n,r,o,a,i,s,l){i.eventTrack("settingsTwoStepEmailController",{category:"Modal"});var c,u=null;e.updateModel={token:null,email:null},l(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=r.hashPassword(n.masterPassword).then(function(e){return c=e,t.twoFactor.getEmail({},{masterPasswordHash:c}).$promise}).then(function(e){return a=e,o.getUserProfile()}).then(function(t){u=t,e.enabled=a.Enabled,e.updateModel.email=e.enabled?a.Email:u.email,e.authed=!0})},e.sendEmail=function(n){if(e.emailError=!1,e.emailSuccess=!1,!n||!n.email||n.email.indexOf("@")<0)return e.emailError=!0,void(e.emailSuccess=!1);e.emailLoading=!0,t.twoFactor.sendEmail({},{masterPasswordHash:c,email:n.email},function(t){e.emailError=!1,e.emailSuccess=!0,e.emailLoading=!1},function(t){e.emailError=!0,e.emailSuccess=!1,e.emailLoading=!1})},e.submit=function(n){var r;n&&n.token?(r=n,e.submitPromise=t.twoFactor.putEmail({},{email:r.email.toLowerCase().trim(),token:r.token.replace(" ",""),masterPasswordHash:c},function(t){i.eventTrack("Enabled Two-step Email"),e.enabled=t.Enabled,r.email=t.Email,r.token=null}).$promise):function(){if(!confirm("Are you sure you want to disable the email provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:c,type:s.twoFactorProvider.email},function(t){i.eventTrack("Disabled Two-step Email"),a.success("Email has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}()};var d=!1;e.close=function(){d=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,r){d||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepRecoverController",["$scope","apiService","$uibModalInstance","cryptoService","$analytics","$timeout",function(e,t,n,r,o,a){o.eventTrack("settingsTwoStepRecoverController",{category:"Modal"}),e.code=null,e.auth=function(n){e.authPromise=r.hashPassword(n.masterPassword).then(function(e){return t.twoFactor.getRecover({},{masterPasswordHash:e}).$promise}).then(function(t){e.code=function(e){if(!e)return null;return e.replace(/(.{4})/g,"$1 ").trim().toUpperCase()}(t.Code),e.authed=!0})},a(function(){$("#masterPassword").focus()}),e.print=function(){if(e.code){o.eventTrack("Print Recovery Code");var t=window.open();t.document.write('<div style="font-size: 18px; text-align: center;"><p>Bitwarden two-step login recovery code:</p><code style="font-family: Menlo, Monaco, Consolas, \'Courier New\', monospace;">'+e.code+'</code></div><p style="text-align: center;">'+new Date+"</p>"),t.print(),t.close()}},e.close=function(){n.close()}}]),angular.module("bit.settings").controller("settingsTwoStepU2fController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout","$window",function(e,t,n,r,o,a,i,s,l,c){var u;i.eventTrack("settingsTwoStepU2fController",{category:"Modal"});var d=!1;e.deviceResponse=null,e.deviceListening=!1,e.deviceError=!1,l(function(){$("#masterPassword").focus()}),e.auth=function(n){e.authPromise=r.hashPassword(n.masterPassword).then(function(e){return u=e,t.twoFactor.getU2f({},{masterPasswordHash:u}).$promise}).then(function(t){return e.enabled=t.Enabled,e.challenge=t.Challenge,e.authed=!0,e.readDevice()})},e.readDevice=function(){d||e.enabled||(console.log("listening for key..."),e.deviceResponse=null,e.deviceError=!1,e.deviceListening=!0,c.u2f.register(e.challenge.AppId,[{version:e.challenge.Version,challenge:e.challenge.Challenge}],[],function(t){if(e.deviceListening=!1,5!==t.errorCode)return t.errorCode?(l(function(){e.deviceError=!0}),void console.log("error: "+t.errorCode)):void l(function(){e.deviceResponse=JSON.stringify(t)});e.readDevice()},10))},e.submit=function(){e.enabled?function(){if(!confirm("Are you sure you want to disable the U2F provider?"))return;e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:u,type:s.twoFactorProvider.u2f},function(t){i.eventTrack("Disabled Two-step U2F"),a.success("U2F has been disabled."),e.enabled=t.Enabled,e.close()}).$promise}():e.submitPromise=t.twoFactor.putU2f({},{deviceResponse:e.deviceResponse,masterPasswordHash:u},function(t){i.eventTrack("Enabled Two-step U2F"),e.enabled=t.Enabled,e.challenge=null,e.deviceResponse=null,e.deviceError=!1}).$promise},e.close=function(){d=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,r){d||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepYubiController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout",function(e,t,n,r,o,a,i,s,l){i.eventTrack("settingsTwoStepYubiController",{category:"Modal"});var c;function u(t){e.enabled=t.Enabled,e.updateModel={key1:{key:t.Key1,existingKey:d(t.Key1,"*",44)},key2:{key:t.Key2,existingKey:d(t.Key2,"*",44)},key3:{key:t.Key3,existingKey:d(t.Key3,"*",44)},nfc:!0===t.Nfc||!t.Enabled}}function d(e,t,n){if(!e||!t||e.length>=n)return e;for(var r=(n-e.length)/t.length,o=0;o<r;o++)e+=t;return e}l(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=r.hashPassword(n.masterPassword).then(function(e){return c=e,t.twoFactor.getYubi({},{masterPasswordHash:c}).$promise}).then(function(e){return a=e,o.getUserProfile()}).then(function(t){t,u(a),e.authed=!0})},e.remove=function(e){e.key=null,e.existingKey=null},e.submit=function(n){e.submitPromise=t.twoFactor.putYubi({},{key1:n.key1.key,key2:n.key2.key,key3:n.key3.key,nfc:n.nfc,masterPasswordHash:c},function(e){i.eventTrack("Saved Two-step YubiKey"),a.success("YubiKey saved."),u(e)}).$promise},e.disable=function(){confirm("Are you sure you want to disable the YubiKey provider?")&&(e.disableLoading=!0,e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:c,type:s.twoFactorProvider.yubikey},function(t){e.disableLoading=!1,i.eventTrack("Disabled Two-step YubiKey"),a.success("YubiKey has been disabled."),e.enabled=t.Enabled,e.close()},function(t){a.error("Failed to disable."),e.disableLoading=!1}).$promise)};var p=!1;e.close=function(){p=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,r){p||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsUpdateKeyController",["$scope","$state","apiService","$uibModalInstance","cipherService","cryptoService","authService","validationService","toastr","$analytics","$q",function(e,t,n,r,o,a,i,s,l,c,u){c.eventTrack("settingsUpdateKeyController",{category:"Modal"}),e.save=function(d){a.getEncKey()?s.addError(d,"MasterPasswordHash","You do not need to update. You are already using the new encryption key.",!0):e.savePromise=a.hashPassword(e.masterPassword).then(function(e){return function(e){var t=a.makeEncKey(null),r=[],i=n.ciphers.list({},function(e){for(var n=[],a=0;a<e.Data.length;a++)e.Data[a].OrganizationId||n.push(e.Data[a]);var i=o.decryptCiphers(n);r=o.encryptCiphers(i,t.encKey)}).$promise,s=[],l=n.folders.list({},function(e){var n=o.decryptFolders(e.Data);s=o.encryptFolders(n,t.encKey)}).$promise,c=a.getPrivateKey("raw"),d=null;c&&(d=a.encrypt(c,t.encKey,"raw"));return u.all([i,l]).then(function(){var o={masterPasswordHash:e,ciphers:r,folders:s,privateKey:d,key:t.encKeyEnc};return n.accounts.putKey(o).$promise},function(){throw"Error while encrypting data."}).then(function(){a.setEncKey(t.encKey,null,!0)})}(e)}).then(function(){return r.dismiss("cancel"),i.logOut(),c.eventTrack("Key Updated"),t.go("frontend.login.info")},function(e){throw e||"Error occurred."}).then(function(){l.success("Please log back in. If you are using other Bitwarden applications, log out and back in to those as well.","Key Updated",{timeOut:1e4})})},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.tools").controller("toolsController",["$scope","$uibModal","apiService","toastr","authService",function(e,t,n,r,o){e.import=function(){t.open({animation:!0,templateUrl:"app/tools/views/toolsImport.html",controller:"toolsImportController"})},e.export=function(){t.open({animation:!0,templateUrl:"app/tools/views/toolsExport.html",controller:"toolsExportController"})}}]),angular.module("bit.tools").controller("toolsExportController",["$scope","apiService","$uibModalInstance","cipherService","$q","toastr","$analytics","constants",function(e,t,n,r,o,a,i,s){function l(){var e=new Date;return"bitwarden_export_"+(e.getFullYear()+""+c(e.getMonth()+1,2)+c(e.getDate(),2)+c(e.getHours(),2)+c(e.getMinutes(),2)+c(e.getSeconds(),2))+".csv"}function c(e,t,n){return n=n||"0",(e+="").length>=t?e:new Array(t-e.length+1).join(n)+e}i.eventTrack("toolsExportController",{category:"Modal"}),e.export=function(n){e.startedExport=!0;var c=[],u=[],d=t.folders.list({},function(e){u=r.decryptFolders(e.Data)}).$promise,p=t.ciphers.list({},function(e){c=r.decryptCiphers(e.Data)}).$promise;o.all([d,p]).then(function(){if(!c.length)return a.error("Nothing to export.","Error!"),void e.close();for(var t={},n=0;n<u.length;n++)t[u[n].id]=u[n];try{var r=[];for(n=0;n<c.length;n++)if(c[n].type===s.cipherType.login||c[n].type===s.cipherType.secureNote){var o,d={folder:c[n].folderId&&c[n].folderId in t?t[c[n].folderId].name:null,favorite:c[n].favorite?1:null,type:null,name:c[n].name,notes:c[n].notes,fields:null,login_uri:null,login_username:null,login_password:null,login_totp:null};if(c[n].fields)for(o=0;o<c[n].fields.length;o++)d.fields?d.fields+="\n":d.fields="",d.fields+=(c[n].fields[o].name||"")+": "+c[n].fields[o].value;switch(c[n].type){case s.cipherType.login:if(d.type="login",d.login_username=c[n].login.username,d.login_password=c[n].login.password,d.login_totp=c[n].login.totp,c[n].login.uris&&c[n].login.uris.length)for(d.login_uri=[],o=0;o<c[n].login.uris.length;o++)d.login_uri.push(c[n].login.uris[o].uri);break;case s.cipherType.secureNote:d.type="note";break;default:continue}r.push(d)}var p=Papa.unparse(r),m=new Blob([p]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(m,l());else{var g=window.document.createElement("a");g.href=window.URL.createObjectURL(m,{type:"text/plain"}),g.download=l(),document.body.appendChild(g),g.click(),document.body.removeChild(g)}i.eventTrack("Exported Data"),a.success("Your data has been exported. Check your browser's downloads folder.","Success!"),e.close()}catch(t){a.error("Something went wrong. Please try again.","Error!"),e.close()}},function(){a.error("Something went wrong. Please try again.","Error!"),e.close()})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.tools").controller("toolsImportController",["$scope","$state","apiService","$uibModalInstance","cryptoService","cipherService","toastr","importService","$analytics","$sce","validationService",function(e,t,n,r,o,a,i,s,l,c,u){function d(o,s,c){if(o.length||s.length){if(s.length){var u=Math.floor(s.length/2),d=s.length-1;if(p(s[0])&&p(s[u])&&p(s[d]))return void m("Data is not formatted correctly. Please check your import file and try again.")}n.ciphers.import({folders:a.encryptFolders(o),ciphers:a.encryptCiphers(s),folderRelationships:c},function(){r.dismiss("cancel"),t.go("backend.user.vault",{refreshFromServer:!0}).then(function(){l.eventTrack("Imported Data",{label:e.model.source}),i.success("Data has been successfully imported into your vault.","Import Success")})},m)}else m("Nothing was imported.")}function p(e){return(null===e.name||"--"===e.name)&&e.login&&(null===e.login.password||""===e.login.password)}function m(t){if(l.eventTrack("Import Data Failed",{label:e.model.source}),r.dismiss("cancel"),t){var n=t.data;if(!n||!n.ValidationErrors)return n&&n.Message?void i.error(n.Message):void i.error(t);var o="";for(var a in n.ValidationErrors)if(n.ValidationErrors.hasOwnProperty(a))for(var s=0;s<n.ValidationErrors[a].length;s++)o+=a+": "+n.ValidationErrors[a][s]+" ";if(""!==o)return void i.error(o)}i.error("Something went wrong. Try again.","Oh No!")}l.eventTrack("toolsImportController",{category:"Modal"}),e.model={source:""},e.source={},e.splitFeatured=!0,e.options=[{id:"bitwardencsv",name:"Bitwarden (csv)",featured:!0,sort:1,instructions:c.trustAsHtml('Export using the web vault (vault.bitwarden.com). Log into the web vault and navigate to "Tools" > "Export".')},{id:"lastpass",name:"LastPass (csv)",featured:!0,sort:2,instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-lastpass/">https://help.bitwarden.com/article/import-from-lastpass/</a>')},{id:"chromecsv",name:"Chrome (csv)",featured:!0,sort:3,instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-chrome/">https://help.bitwarden.com/article/import-from-chrome/</a>')},{id:"firefoxpasswordexportercsvxml",name:"Firefox Password Exporter (xml)",featured:!0,sort:4,instructions:c.trustAsHtml('Use the <a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/password-exporter/">Password Exporter</a> addon for FireFox to export your passwords to a XML file. After installing the addon, type <code>about:addons</code> in your FireFox navigation bar. Locate the Password Exporter addon and click the "Options" button. In the dialog that pops up, click the "Export Passwords" button to save the XML file.')},{id:"keepass2xml",name:"KeePass 2 (xml)",featured:!0,sort:5,instructions:c.trustAsHtml('Using the KeePass 2 desktop application, navigate to "File" > "Export" and select the KeePass XML (2.x) option.')},{id:"keepassxcsv",name:"KeePassX (csv)",instructions:c.trustAsHtml('Using the KeePassX desktop application, navigate to "Database" > "Export to CSV file" and save the CSV file.')},{id:"dashlanecsv",name:"Dashlane (csv)",featured:!0,sort:7,instructions:c.trustAsHtml('Using the Dashlane desktop application, navigate to "File" > "Export" > "Unsecured archive (readable) in CSV format" and save the CSV file.')},{id:"1password1pif",name:"1Password (1pif)",featured:!0,sort:6,instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-1password/">https://help.bitwarden.com/article/import-from-1password/</a>')},{id:"1password6wincsv",name:"1Password 6 Windows (csv)",instructions:c.trustAsHtml('See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-1password/">https://help.bitwarden.com/article/import-from-1password/</a>')},{id:"roboformhtml",name:"RoboForm (html)",instructions:c.trustAsHtml('Using the RoboForm Editor desktop application, navigate to "RoboForm" (top left) > "Print List" > "Logins". When the following print dialog pops up click on the "Save" button and save the HTML file.')},{id:"keepercsv",name:"Keeper (csv)",instructions:c.trustAsHtml('Log into the Keeper web vault (keepersecurity.com/vault). Navigate to "Backup" (top right) and find the "Export to Text File" option. Click "Export Now" to save the TXT/CSV file.')},{id:"enpasscsv",name:"Enpass (csv)",instructions:c.trustAsHtml('Using the Enpass desktop application, navigate to "File" > "Export" > "As CSV". Select "Yes" to the warning alert and save the CSV file. Note that the importer only fully supports files exported while Enpass is set to the English language, so adjust your settings accordingly.')},{id:"safeincloudxml",name:"SafeInCloud (xml)",instructions:c.trustAsHtml('Using the SaveInCloud desktop application, navigate to "File" > "Export" > "As XML" and save the XML file.')},{id:"pwsafexml",name:"Password Safe (xml)",instructions:c.trustAsHtml('Using the Password Safe desktop application, navigate to "File" > "Export To" > "XML format..." and save the XML file.')},{id:"stickypasswordxml",name:"Sticky Password (xml)",instructions:c.trustAsHtml('Using the Sticky Password desktop application, navigate to "Menu" (top right) > "Export" > "Export all". Select the unencrypted format XML option and then the "Save to file" button. Save the XML file.')},{id:"msecurecsv",name:"mSecure (csv)",instructions:c.trustAsHtml('Using the mSecure desktop application, navigate to "File" > "Export" > "CSV File..." and save the CSV file.')},{id:"truekeycsv",name:"True Key (csv)",instructions:c.trustAsHtml('Using the True Key desktop application, click the gear icon (top right) and then navigate to "App Settings". Click the "Export" button, enter your password and save the CSV file.')},{id:"passwordbossjson",name:"Password Boss (json)",instructions:c.trustAsHtml('Using the Password Boss desktop application, navigate to "File" > "Export data" > "Password Boss JSON - not encrypted" and save the JSON file.')},{id:"zohovaultcsv",name:"Zoho Vault (csv)",instructions:c.trustAsHtml('Log into the Zoho web vault (vault.zoho.com). Navigate to "Tools" > "Export Secrets". Select "All Secrets" and click the "Zoho Vault Format CSV" button. Highlight and copy the data from the textarea. Open a text editor like Notepad and paste the data. Save the data from the text editor as <code>zoho_export.csv</code>.')},{id:"splashidcsv",name:"SplashID (csv)",instructions:c.trustAsHtml('Using the SplashID Safe desktop application, click on the SplashID blue lock logo in the top right corner. Navigate to "Export" > "Export as CSV" and save the CSV file.')},{id:"passworddragonxml",name:"Password Dragon (xml)",instructions:c.trustAsHtml('Using the Password Dragon desktop application, navigate to "File" > "Export" > "To XML". In the dialog that pops up select "All Rows" and check all fields. Click the "Export" button and save the XML file.')},{id:"padlockcsv",name:"Padlock (csv)",instructions:c.trustAsHtml('Using the Padlock desktop application, click the hamburger icon in the top left corner and navigate to "Settings". Click the "Export Data" option. Ensure that the "CSV" option is selected from the dropdown. Highlight and copy the data from the textarea. Open a text editor like Notepad and paste the data. Save the data from the text editor as <code>padlock_export.csv</code>.')},{id:"clipperzhtml",name:"Clipperz (html)",instructions:c.trustAsHtml('Log into the Clipperz web application (clipperz.is/app). Click the hamburger menu icon in the top right to expand the navigation bar. Navigate to "Data" > "Export". Click the "download HTML+JSON" button to save the HTML file.')},{id:"avirajson",name:"Avira (json)",instructions:c.trustAsHtml('Using the Avira browser extension, click your username in the top right corner and navigate to "Settings". Locate the "Export Data" section and click "Export". In the dialog that pops up, click the "Export Password Manager Data" button to save the TXT/JSON file.')},{id:"saferpasscsv",name:"SaferPass (csv)",instructions:c.trustAsHtml('Using the SaferPass browser extension, click the hamburger icon in the top left corner and navigate to "Settings". Click the "Export accounts" button to save the CSV file.')},{id:"upmcsv",name:"Universal Password Manager (csv)",instructions:c.trustAsHtml('Using the Universal Password Manager desktop application, navigate to "Database" > "Export" and save the CSV file.')},{id:"ascendocsv",name:"Ascendo DataVault (csv)",instructions:c.trustAsHtml('Using the Ascendo DataVault desktop application, navigate to "Tools" > "Export". In the dialog that pops up, select the "All Items (DVX, CSV)" option. Click the "Ok" button to save the CSV file.')},{id:"meldiumcsv",name:"Meldium (csv)",instructions:c.trustAsHtml('Using the Meldium web vault, navigate to "Settings". Locate the "Export data" function and click "Show me my data" to save the CSV file.')},{id:"passkeepcsv",name:"PassKeep (csv)",instructions:c.trustAsHtml('Using the PassKeep mobile app, navigate to "Backup/Restore". Locate the "CSV Backup/Restore" section and click "Backup to CSV" to save the CSV file.')},{id:"operacsv",name:"Opera (csv)",instructions:c.trustAsHtml('The process for importing from Opera is exactly the same as importing from Google Chrome. See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-chrome/">https://help.bitwarden.com/article/import-from-chrome/</a>')},{id:"vivaldicsv",name:"Vivaldi (csv)",instructions:c.trustAsHtml('The process for importing from Vivaldi is exactly the same as importing from Google Chrome. See detailed instructions on our help site at <a target="_blank" href="https://help.bitwarden.com/article/import-from-chrome/">https://help.bitwarden.com/article/import-from-chrome/</a>')},{id:"gnomejson",name:"GNOME Passwords and Keys/Seahorse (json)",instructions:c.trustAsHtml('Make sure you have python-keyring and python-gnomekeyring installed. Save the <a target="_blank" href="http://bit.ly/2sMldAI">GNOME Keyring Import/Export</a> python script by Luke Plant to your desktop as <code>pw_helper.py</code>. Open terminal and run <code>chmod +rx Desktop/pw_helper.py</code> and then <code>python Desktop/pw_helper.py export Desktop/my_passwords.json</code>. Then upload the resulting <code>my_passwords.json</code> file here to Bitwarden.')}],e.setSource=function(){for(var t=0;t<e.options.length;t++)if(e.options[t].id===e.model.source){e.source=e.options[t];break}},e.setSource(),e.import=function(t,n){if(t.source&&""!==t.source){var r=document.getElementById("file").files[0];r||t.fileContents&&""!==t.fileContents?(e.processing=!0,s.import(t.source,r||t.fileContents,d,m)):u.addError(n,"file","Select the import file or copy/paste the import file contents.",!0)}else u.addError(n,"source","Select the format of the import file.",!0)},e.close=function(){r.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultAddCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","selectedFolder","$analytics","checkedFavorite","$rootScope","authService","$uibModal","constants","$filter","selectedType",function(e,t,n,r,o,a,i,s,l,c,u,d,p,m,g){function f(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("vaultAddCipherController",{category:"Modal"}),e.folders=c.vaultFolders,e.constants=p,e.selectedType=g?g.toString():p.cipherType.login.toString(),e.cipher={folderId:i?i.id:null,favorite:!0===l,type:g||p.cipherType.login,login:{uris:[{uri:null,match:null,matchValue:null}]},identity:{},card:{},secureNote:{type:0}},u.getUserProfile().then(function(t){e.useTotp=t.premium}),e.typeChanged=function(){e.cipher.type=parseInt(e.selectedType)},e.savePromise=null,e.save=function(){var r=o.encryptCipher(e.cipher);e.savePromise=t.ciphers.post(r,function(e){s.eventTrack("Created Cipher");var t=o.decryptCipherPreview(e);n.close(t)}).$promise},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Add"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addUri=function(){e.cipher.login&&(e.cipher.login.uris||(e.cipher.login.uris=[]),e.cipher.login.uris.push({uri:null,match:null,matchValue:null}))},e.removeUri=function(t){if(e.cipher.login&&e.cipher.login.uris){var n=e.cipher.login.uris.indexOf(t);n>-1&&e.cipher.login.uris.splice(n,1)}},e.uriMatchChanged=function(e){!e.matchValue&&0!==e.matchValue||""===e.matchValue?e.match=null:e.match=parseInt(e.matchValue)},e.addField=function(){e.cipher.fields||(e.cipher.fields=[]),e.cipher.fields.push({type:p.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.toggleFavorite=function(){e.cipher.favorite=!e.cipher.favorite},e.clipboardSuccess=function(e){e.clearSelection(),f(e)},e.clipboardError=function(e,t){t&&f(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.folderSort=function(e){return e.id?e.name.toLowerCase():""},e.close=function(){n.dismiss("close")},e.showUpgrade=function(){d.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}}]),angular.module("bit.vault").controller("vaultAddFolderController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","$analytics",function(e,t,n,r,o,a){a.eventTrack("vaultAddFolderController",{category:"Modal"}),e.savePromise=null,e.save=function(r){var i=o.encryptFolder(r);e.savePromise=t.folders.post(i,function(e){a.eventTrack("Created Folder");var t=o.decryptFolder(e);n.close(t)}).$promise},e.close=function(){n.dismiss("close")}}]),angular.module("bit.vault").controller("vaultAttachmentsController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","cipherId","$analytics","validationService","toastr","$timeout","authService","$uibModal",function(e,t,n,r,o,a,i,s,l,c,u,d){i.eventTrack("vaultAttachmentsController",{category:"Modal"}),e.cipher={},e.readOnly=!0,e.loading=!0,e.isPremium=!0,e.canUseAttachments=!0;var p=!1;function m(){return e.cipher.organizationId?r.getOrgKey(e.cipher.organizationId):null}u.getUserProfile().then(function(n){return e.isPremium=n.premium,t.ciphers.get({id:a}).$promise}).then(function(t){e.cipher=o.decryptCipher(t),e.readOnly=!e.cipher.edit,e.canUseAttachments=e.isPremium||e.cipher.organizationId,e.loading=!1},function(){e.loading=!1}),e.save=function(n){var r=document.getElementById("file"),c=r.files;c&&c.length?e.savePromise=o.encryptAttachmentFile(m(),c[0]).then(function(e){var n=new FormData,r=new Blob([e.data],{type:"application/octet-stream"});return n.append("data",r,e.fileName),t.ciphers.postAttachment({id:a},n).$promise}).then(function(t){i.eventTrack("Added Attachment"),e.cipher=o.decryptCipher(t),r.type="",r.type="file",r.value=""},function(e){var t=s.parseErrors(e);l.error(t.length?t[0]:"An error occurred.")}):s.addError(n,"file","Select a file.",!0)},e.download=function(t){if(t.loading=!0,!e.canUseAttachments)return t.loading=!1,void alert("Premium membership is required to use this feature.");o.downloadAndDecryptAttachment(m(),t,!0).then(function(e){c(function(){t.loading=!1})},function(){c(function(){t.loading=!1})})},e.remove=function(n){confirm("Are you sure you want to delete this attachment ("+n.fileName+")?")&&(n.loading=!0,t.ciphers.delAttachment({id:a,attachmentId:n.id}).$promise.then(function(){n.loading=!1,i.eventTrack("Deleted Attachment");var t=e.cipher.attachments.indexOf(n);t>-1&&e.cipher.attachments.splice(t,1)},function(){l.error("Cannot delete attachment."),n.loading=!1}))},e.close=function(){n.dismiss("cancel")},e.$on("modal.closing",function(t,r,o){p||(t.preventDefault(),p=!0,n.close(!!e.cipher.attachments&&e.cipher.attachments.length>0))}),e.showUpgrade=function(){d.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}}]),angular.module("bit.vault").controller("vaultCipherCollectionsController",["$scope","apiService","$uibModalInstance","cipherService","cipherId","$analytics",function(e,t,n,r,o,a){a.eventTrack("vaultCipherCollectionsController",{category:"Modal"}),e.cipher={},e.readOnly=!1,e.loadingCipher=!0,e.loadingCollections=!0,e.selectedCollections={},e.collections=[];var i=null;n.opened.then(function(){t.ciphers.getDetails({id:o}).$promise.then(function(t){if(e.loadingCipher=!1,e.readOnly=!t.Edit,t.Edit&&t.OrganizationId){1===t.Type&&(e.cipher=r.decryptCipherPreview(t));var n={};if(t.CollectionIds)for(var o=0;o<t.CollectionIds.length;o++)n[t.CollectionIds[o]]=null;return{cipher:t,cipherCollections:n}}return null}).then(function(n){return n?(i=n,t.collections.listMe({writeOnly:!0}).$promise):(e.loadingCollections=!1,!1)}).then(function(t){if(!1!==t){for(var n=[],o={},a=t.Data,s=0;s<a.length;s++)if(a[s].OrganizationId===i.cipher.OrganizationId){a[s].Id in i.cipherCollections&&(o[a[s].Id]=!0);var l=r.decryptCollection(a[s]);n.push(l)}e.loadingCollections=!1,e.collections=n,e.selectedCollections=o}})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.collections.length;r++)n[e.collections[r].id]=!0;e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]=!0},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return Object.keys(e.selectedCollections).length===e.collections.length},e.submit=function(){var r={collectionIds:[]};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&r.collectionIds.push(i);e.submitPromise=t.ciphers.putCollections({id:o},r).$promise.then(function(e){a.eventTrack("Edited Cipher Collections"),n.close({action:"collectionsEdit",collectionIds:r.collectionIds})})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultController",["$scope","$uibModal","apiService","$filter","cryptoService","authService","toastr","cipherService","$q","$localStorage","$timeout","$rootScope","$state","$analytics","constants","validationService",function(e,t,n,r,o,a,i,s,l,c,u,d,p,m,g,f){function h(t){d.vaultCiphers=e.ciphers=r("orderBy")(t,["sort","name","subTitle"]);var n=function(e,t){var n=[],r=0,o=e.length;for(;r<o;)n.push(e.slice(r,r+=t));return n}(d.vaultCiphers,200);if(n.length>0){e.ciphers=n[0];var o=200;angular.forEach(n,function(t,n){n>0&&u(function(){Array.prototype.push.apply(e.ciphers,t)},o+=200)})}e.loadingCiphers=!1}function v(){d.vaultCiphers=e.ciphers=r("orderBy")(d.vaultCiphers,["name","subTitle"])}function y(){e.selectedFolder=void 0,e.selectedCollection=void 0,e.selectedType=void 0,e.selectedFavorites=!1,e.selectedAll=!1}function b(){$.AdminLTE&&$.AdminLTE.layout&&u(function(){$.AdminLTE.layout.fix()},0)}function w(e,t,n){return n.indexOf(e)===t}function C(){return $('input[name="cipherSelection"]:checked').map(function(){return $(this).val()}).get().filter(w)}function S(e){$('input[name="cipherSelection"]').prop("checked",e)}function k(t){var n=d.vaultCiphers.indexOf(t);n>-1&&d.vaultCiphers.splice(n,1),(n=e.ciphers.indexOf(t))>-1&&e.ciphers.splice(n,1)}e.loadingCiphers=!0,e.loadingGroupings=!0,e.ciphers=[],e.folders=[],e.collections=[],e.constants=g,e.filter=void 0,e.selectedType=void 0,e.selectedFolder=void 0,e.selectedCollection=void 0,e.selectedFavorites=!1,e.selectedAll=!0,e.selectedTitle="All",e.selectedIcon="fa-th",p.params.refreshFromServer&&(d.vaultFolders=d.vaultCollections=d.vaultCiphers=null),e.$on("$viewContentLoaded",function(){if(u(function(){$("body").hasClass("control-sidebar-open")&&$("#search").focus()},500),(d.vaultFolders||d.vaultCollections)&&d.vaultCiphers)return e.loadingCiphers=e.loadingGroupings=!1,void h(d.vaultCiphers);var t,r,o,a,i;t=[{id:null,name:"No Folder"}],r=[],o=n.collections.listMe({writeOnly:!1},function(e){for(var t=0;t<e.Data.length;t++){var n=s.decryptCollection(e.Data[t],null,!0);r.push(n)}}).$promise,a=n.folders.list({},function(e){for(var n=0;n<e.Data.length;n++){var r=s.decryptFolderPreview(e.Data[n]);t.push(r)}}).$promise,i=l.all([o,a]).then(function(){d.vaultCollections=r,d.vaultFolders=t,e.loadingGroupings=!1}),n.ciphers.list({},function(e){for(var t=[],n=0;n<e.Data.length;n++){var r=s.decryptCipherPreview(e.Data[n]);t.push(r)}i.then(function(){h(t)})}).$promise}),e.groupingSort=function(e){return e.id?e.name.toLowerCase():""},e.clipboardError=function(e){alert("Your web browser does not support easy clipboard copying. Edit the item and copy it manually instead.")},e.editCipher=function(n){t.open({animation:!0,templateUrl:"app/vault/views/vaultEditCipher.html",controller:"vaultEditCipherController",resolve:{cipherId:function(){return n.id}}}).result.then(function(t){if("edit"===t.action){var r=e.ciphers.indexOf(n);r>-1&&(t.data.collectionIds=d.vaultCiphers[r].collectionIds,d.vaultCiphers[r]=t.data),v()}else"partialEdit"===t.action?(n.folderId=t.data.folderId,n.favorite=t.data.favorite):"delete"===t.action&&k(n)})},e.$on("vaultAddCipher",function(t,n){e.addCipher()}),e.addCipher=function(){t.open({animation:!0,templateUrl:"app/vault/views/vaultAddCipher.html",controller:"vaultAddCipherController",resolve:{selectedFolder:function(){return e.selectedFolder},selectedType:function(){return e.selectedType},checkedFavorite:function(){return e.selectedFavorites}}}).result.then(function(e){d.vaultCiphers.push(e),v()})},e.deleteCipher=function(e){confirm("Are you sure you want to delete this item ("+e.name+")?")&&n.ciphers.del({id:e.id},function(){m.eventTrack("Deleted Item"),k(e)})},e.attachments=function(e){a.getUserProfile().then(function(t){return{isPremium:t.premium,orgUseStorage:e.organizationId&&!!t.organizations[e.organizationId].maxStorageGb}}).then(function(n){if(!e.hasAttachments){if(e.organizationId&&!n.orgUseStorage)return void t.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return e.organizationId}}});if(!e.organizationId&&!n.isPremium)return void t.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}e.organizationId||o.getEncKey()?t.open({animation:!0,templateUrl:"app/vault/views/vaultAttachments.html",controller:"vaultAttachmentsController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){e.hasAttachments=t}):i.error("You cannot use this feature until you update your encryption key.","Feature Unavailable")})},e.editFolder=function(e){e.id&&t.open({animation:!0,templateUrl:"app/vault/views/vaultEditFolder.html",controller:"vaultEditFolderController",size:"sm",resolve:{folderId:function(){return e.id}}}).result.then(function(t){e.name=t.name})},e.$on("vaultAddFolder",function(t,n){e.addFolder()}),e.addFolder=function(){t.open({animation:!0,templateUrl:"app/vault/views/vaultAddFolder.html",controller:"vaultAddFolderController",size:"sm"}).result.then(function(e){d.vaultFolders.push(e)})},e.deleteFolder=function(t){t.id&&confirm("Are you sure you want to delete this folder ("+t.name+')? Any items will be moved to "No Folder".')&&n.folders.del({id:t.id},function(){m.eventTrack("Deleted Folder");var n=d.vaultFolders.indexOf(t);n>-1&&(d.vaultFolders.splice(n,1),e.filterAll())})},e.share=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultShareCipher.html",controller:"vaultShareCipherController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){e.organizationId=t})},e.editCollections=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultCipherCollections.html",controller:"vaultCipherCollectionsController",resolve:{cipherId:function(){return e.id}}}).result.then(function(t){t.collectionIds&&!t.collectionIds.length?k(e):t.collectionIds&&(e.collectionIds=t.collectionIds)})},e.filterCollection=function(t){y(),e.selectedCollection=t,e.selectedIcon="fa-cube",e.filter=function(e){return e.collectionIds&&e.collectionIds.indexOf(t.id)>-1},b()},e.filterFolder=function(t){y(),e.selectedFolder=t,e.selectedIcon="fa-folder-open"+(t.id?"":"-o"),e.filter=function(e){return e.folderId===t.id},b()},e.filterType=function(t){switch(y(),e.selectedType=t,t){case g.cipherType.login:e.selectedTitle="Login",e.selectedIcon="fa-globe";break;case g.cipherType.card:e.selectedTitle="Card",e.selectedIcon="fa-credit-card";break;case g.cipherType.identity:e.selectedTitle="Identity",e.selectedIcon="fa-id-card-o";break;case g.cipherType.secureNote:e.selectedTitle="Secure Note",e.selectedIcon="fa-sticky-note-o"}e.filter=function(e){return e.type===t},b()},e.filterFavorites=function(){y(),e.selectedFavorites=!0,e.selectedTitle="Favorites",e.selectedIcon="fa-star",e.filter=function(e){return!!e.favorite},b()},e.filterAll=function(){y(),e.selectedAll=!0,e.selectedTitle="All",e.selectedIcon="fa-th",e.filter=null,b()},e.cipherFilter=function(){return function(t){return!e.filter||e.filter(t)}},e.unselectAll=function(){S(!1)},e.selectAll=function(){S(!0)},e.select=function(e){var t=$(e.currentTarget).closest("tr").find('input[name="cipherSelection"]');t.prop("checked",!t.prop("checked"))},e.bulkMove=function(){var e=C();0!==e.length?t.open({animation:!0,templateUrl:"app/vault/views/vaultMoveCiphers.html",controller:"vaultMoveCiphersController",size:"sm",resolve:{ids:function(){return e}}}).result.then(function(t){for(var n=0;n<e.length;n++){var o=r("filter")(d.vaultCiphers,{id:e[n]});o.length&&(o[0].folderId=t)}S(!1),v(),i.success("Items have been moved!")}):alert("You have not selected anything.")},e.bulkDelete=function(){var t=C();0!==t.length?confirm("Are you sure you want to delete the selected items (total: "+t.length+")?")&&(e.actionLoading=!0,n.ciphers.delMany({ids:t},function(){m.eventTrack("Bulk Deleted Items");for(var n=0;n<t.length;n++){var o=r("filter")(d.vaultCiphers,{id:t[n]});o.length&&o[0].edit&&k(o[0])}S(!1),e.actionLoading=!1,i.success("Items have been deleted!")},function(t){var n=f.parseErrors(t);i.error(n.length?n[0]:"An error occurred."),e.actionLoading=!1})):alert("You have not selected anything.")}}]),angular.module("bit.vault").controller("vaultEditCipherController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","cipherId","$analytics","$rootScope","authService","$uibModal","constants","$filter",function(e,t,n,r,o,a,i,s,l,c,u,d,p){function m(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("vaultEditCipherController",{category:"Modal"}),e.folders=l.vaultFolders,e.cipher={},e.readOnly=!1,e.constants=d,c.getUserProfile().then(function(n){return e.useTotp=n.premium,t.ciphers.get({id:i}).$promise}).then(function(t){e.cipher=o.decryptCipher(t),e.readOnly=!e.cipher.edit,e.useTotp=e.useTotp||e.cipher.organizationUseTotp,function(){if(e.cipher.login&&e.cipher.login.uris)for(var t=0;t<e.cipher.login.uris.length;t++)e.cipher.login.uris[t].matchValue=e.cipher.login.uris[t].match||0===e.cipher.login.uris[t].match?e.cipher.login.uris[t].match.toString():""}()}),e.save=function(r){if(e.readOnly)e.savePromise=t.ciphers.putPartial({id:i},{folderId:r.folderId,favorite:r.favorite},function(e){s.eventTrack("Partially Edited Cipher"),n.close({action:"partialEdit",data:{id:i,favorite:r.favorite,folderId:r.folderId&&""!==r.folderId?r.folderId:null}})}).$promise;else{var a=o.encryptCipher(r,e.cipher.type);e.savePromise=t.ciphers.put({id:i},a,function(e){s.eventTrack("Edited Cipher");var t=o.decryptCipherPreview(e);n.close({action:"edit",data:t})}).$promise}},e.generatePassword=function(){e.cipher.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Edit"),e.cipher.login.password=a.generatePassword({length:14,special:!0}))},e.addUri=function(){e.cipher.login&&(e.cipher.login.uris||(e.cipher.login.uris=[]),e.cipher.login.uris.push({uri:null,match:null,matchValue:null}))},e.removeUri=function(t){if(e.cipher.login&&e.cipher.login.uris){var n=e.cipher.login.uris.indexOf(t);n>-1&&e.cipher.login.uris.splice(n,1)}},e.uriMatchChanged=function(e){!e.matchValue&&0!==e.matchValue||""===e.matchValue?e.match=null:e.match=parseInt(e.matchValue)},e.addField=function(){e.cipher.fields||(e.cipher.fields=[]),e.cipher.fields.push({type:d.fieldType.text.toString(),name:null,value:null})},e.removeField=function(t){var n=e.cipher.fields.indexOf(t);n>-1&&e.cipher.fields.splice(n,1)},e.toggleFavorite=function(){e.cipher.favorite=!e.cipher.favorite},e.clipboardSuccess=function(e){e.clearSelection(),m(e)},e.clipboardError=function(e,t){t&&m(e),alert("Your web browser does not support easy clipboard copying. Copy it manually instead.")},e.folderSort=function(e){return e.id?e.name.toLowerCase():""},e.delete=function(){confirm("Are you sure you want to delete this item ("+e.cipher.name+")?")&&t.ciphers.del({id:e.cipher.id},function(){s.eventTrack("Deleted Cipher From Edit"),n.close({action:"delete",data:e.cipher.id})})},e.close=function(){n.dismiss("cancel")},e.showUpgrade=function(){u.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}}]),angular.module("bit.vault").controller("vaultEditFolderController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","folderId","$analytics",function(e,t,n,r,o,a,i){i.eventTrack("vaultEditFolderController",{category:"Modal"}),e.folder={},t.folders.get({id:a},function(t){e.folder=o.decryptFolder(t)}),e.savePromise=null,e.save=function(r){var s=o.encryptFolder(r);e.savePromise=t.folders.put({id:a},s,function(e){i.eventTrack("Edited Folder");var t=o.decryptFolder(e);n.close(t)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultMoveCiphersController",["$scope","apiService","$uibModalInstance","ids","$analytics","$rootScope","$filter",function(e,t,n,r,o,a,i){o.eventTrack("vaultMoveCiphersController",{category:"Modal"}),e.folders=a.vaultFolders,e.count=r.length,e.save=function(){e.savePromise=t.ciphers.moveMany({ids:r,folderId:e.folderId},function(){o.eventTrack("Bulk Moved Ciphers"),n.close(e.folderId||null)}).$promise},e.folderSort=function(e){return e.id?e.name.toLowerCase():"!"},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultShareCipherController",["$scope","apiService","$uibModalInstance","authService","cipherService","cipherId","$analytics","$state","cryptoService","$q","toastr",function(e,t,n,r,o,a,i,s,l,c,u){i.eventTrack("vaultShareCipherController",{category:"Modal"}),e.model={},e.cipher={},e.collections=[],e.selectedCollections={},e.organizations=[];var d={};e.loadingCollections=!0,e.loading=!0,e.readOnly=!1,t.ciphers.get({id:a}).$promise.then(function(t){return e.readOnly=!t.Edit,t.Edit&&(e.cipher=o.decryptCipher(t)),t.Edit}).then(function(t){if(e.loading=!1,t)return r.getUserProfile()}).then(function(n){if(n&&n.organizations){var r=[],a=!1;for(var i in n.organizations)n.organizations.hasOwnProperty(i)&&n.organizations[i].enabled&&(r.push({id:n.organizations[i].id,name:n.organizations[i].name}),d[n.organizations[i].id]=0,a||(a=!0,e.model.organizationId=n.organizations[i].id));e.organizations=r,t.collections.listMe({writeOnly:!0},function(t){for(var n=[],r=0;r<t.Data.length;r++){var a=o.decryptCollection(t.Data[r]);a.organizationId=t.Data[r].OrganizationId,n.push(a),d[a.organizationId]++}e.collections=n,e.loadingCollections=!1})}}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var r=0;r<e.collections.length;r++)e.model.organizationId&&e.collections[r].organizationId===e.model.organizationId&&(n[e.collections[r].id]=!0);e.selectedCollections=n},e.toggleCollectionSelection=function(t){t in e.selectedCollections?delete e.selectedCollections[t]:e.selectedCollections[t]=!0},e.collectionSelected=function(t){return t.id in e.selectedCollections},e.allSelected=function(){return!!e.model.organizationId&&Object.keys(e.selectedCollections).length===d[e.model.organizationId]},e.orgChanged=function(){e.selectedCollections={}},e.submitPromise=null,e.submit=function(r){var s=l.getOrgKey(r.organizationId),d=!1,p=[];if(e.cipher.attachments)for(var m=0;m<e.cipher.attachments.length;m++)!function(e){var n=o.downloadAndDecryptAttachment(null,e,!1).then(function(e){return l.encryptToBytes(e.buffer,s)}).then(function(n){if(!d){var o=new FormData,i=new Blob([n],{type:"application/octet-stream"}),c=l.encrypt(e.fileName,s);return o.append("data",i,c),t.ciphers.postShareAttachment({id:a,attachmentId:e.id,orgId:r.organizationId},o).$promise}},function(e){d=!0});p.push(n)}(e.cipher.attachments[m]);e.submitPromise=c.all(p).then(function(){if(!d){e.cipher.organizationId=r.organizationId;var n={collectionIds:[],cipher:o.encryptCipher(e.cipher,e.cipher.type,null,!0)};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&n.collectionIds.push(i);return t.ciphers.putShare({id:a},n).$promise}}).then(function(e){i.eventTrack("Shared Cipher"),u.success("Item has been shared."),n.close(r.organizationId)})},e.close=function(){n.dismiss("cancel")},e.createOrg=function(){s.go("backend.user.settingsCreateOrg").then(function(){n.dismiss("cancel")})}}]); |