1
0
mirror of https://github.com/bitwarden/web synced 2025-12-06 00:03:28 +00:00
Files
web/js/app.min.js
2017-08-04 13:12:10 -04:00

7 lines
200 KiB
JavaScript

angular.module("bit",["ui.router","ngMessages","angular-jwt","ui.bootstrap.showErrors","toastr","angulartics","angulartics.google.analytics","angular-stripe","credit-cards","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:"https://api.bitwarden.com",identityUri:"https://identity.bitwarden.com",stripeKey:"pk_live_bpN0P37nMxrMQkcaHXtAybJk",braintreeKey:"production_qfbsv8kc_njj2zjtyngtjmbjd",version:"1.14.3",environment:"Production"}),angular.module("bit.accounts",["ui.bootstrap","ngCookies"]),angular.module("bit.filters",[]),angular.module("bit.directives",[]),angular.module("bit.global",[]),angular.module("bit.organization",["ui.bootstrap"]),angular.module("bit.reports",["toastr","ngSanitize"]),angular.module("bit.settings",["ui.bootstrap","toastr"]),angular.module("bit.services",["ngResource","ngStorage","angular-jwt"]),angular.module("bit.tools",["ui.bootstrap","toastr"]),angular.module("bit.vault",["ui.bootstrap","ngclipboard"]),angular.module("bit").factory("apiInterceptor",["$injector","$q","toastr",function(e,t,n){return{request:function(e){return e},response:function(o){return 401!==o.status&&403!==o.status||(e.get("authService").logOut(),e.get("$state").go("frontend.login.info").then(function(){n.warning("Your login session has expired.","Logged out")})),o||t.when(o)},responseError:function(o){return 401!==o.status&&403!==o.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(o)}}}]),angular.module("bit").config(["$stateProvider","$urlRouterProvider","$httpProvider","jwtInterceptorProvider","jwtOptionsProvider","$uibTooltipProvider","toastrConfig","$locationProvider","$qProvider","stripeProvider","appSettings",function(e,t,n,o,r,a,i,s,l,c,u){l.errorOnUnhandledRejections(!1),s.hashPrefix(""),r.config({urlParam:"access_token3",whiteListedDomains:["api.bitwarden.com","preview-api.bitwarden.com","localhost","192.168.1.3"]});var d;o.tokenGetter=["options","tokenService","authService",function(e,t,n){if(0===e.url.indexOf(u.apiUri)){if(d)return d;var o=t.getToken();if(o)return t.tokenNeedsRefresh(o)?d=n.refreshAccessToken().then(function(e){return d=null,e||o}):o}}],c.setPublishableKey(u.stripeKey),angular.extend(i,{closeButton:!0,progressBar:!0,showMethod:"slideDown",target:".toast-target"}),a.options({popupDelay:600,appendToBody:!0}),n.defaults.headers.post&&(n.defaults.headers.post={}),n.defaults.headers.post["Content-Type"]="text/plain; charset=utf-8",(-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.shared",{url:"^/shared",templateUrl:"app/vault/views/vaultShared.html",controller:"vaultSharedController",data:{pageTitle:"Shared"}}).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.user.apps",{url:"^/apps",templateUrl:"app/views/apps.html",controller:"appsController",data:{pageTitle:"Get the Apps"}}).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",templateUrl:"app/organization/views/organizationPeople.html",controller:"organizationPeopleController",data:{pageTitle:"Organization People"}}).state("backend.org.collections",{url:"/organization/:orgId/collections",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",templateUrl:"app/organization/views/organizationVault.html",controller:"organizationVaultController",data:{pageTitle:"Organization Vault"}}).state("backend.org.groups",{url:"/organization/:orgId/groups",templateUrl:"app/organization/views/organizationGroups.html",controller:"organizationGroupsController",data:{pageTitle:"Organization Groups"}}).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.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(o,r,a){if(!r.data||!r.data.authorize){if(r.data&&r.data.skipAuthorize)return;if(!t.isAuthenticated())return;return o.preventDefault(),void n.go("backend.user.vault")}if(!t.isAuthenticated())return o.preventDefault(),t.logOut(),void n.go("frontend.login.info");r.name.indexOf("backend.org.")>-1&&a.orgId&&(e.vaultLogins=e.vaultFolders=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||(o.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},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},personal:{basePrice:1,annualBasePrice:12,baseSeats:5,seatPrice:1,annualSeatPrice:12,maxAdditionalSeats:5,annualPlanType:"personalAnnually",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,o,r,a,i,s,l,c,u,d,p,m){function g(e){for(var t=Object.keys(e),n=null,o=-1,r=0;r<t.length;r++){var a=p("filter")(s.twoFactorProviderInfo,{type:t[r],active:!0});if(a.length&&a[0].priority>o){if(a[0].type===s.twoFactorProvider.u2f&&!u2f.isSupported)continue;n=a[0].type,o=a[0].priority}}return null===n?null:parseInt(n)}function f(e){if(h())return e;for(var t=Object.keys(e),n=[],o=0;o<t.length;o++){p("filter")(s.twoFactorProviderInfo,{type:t[o],active:!0,requiresUsb:!1}).length&&n.push(e[t[o]])}return n}function h(){var e=!1;return function(t){(/(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(t)||/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(t.substr(0,4)))&&(e=!0)}(navigator.userAgent||navigator.vendor||window.opera),!e&&!navigator.userAgent.match(/iPad/i)}function v(){e.returnState?i.go(e.returnState.name,e.returnState.params):i.go("backend.user.vault")}function y(){w=!0;var t;if(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){w=!1,t=e.twoFactorProviders[s.twoFactorProvider.u2f];var n=JSON.parse(t.Challenges);b(n)}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))}function b(t){w||t.length<1||e.twoFactorProvider!==s.twoFactorProvider.u2f||(console.log("listening for u2f key..."),d.u2f.sign(t[0].appId,t[0].challenge,[{version:t[0].version,keyHandle:t[0].keyHandle}],function(n){if(e.twoFactorProvider===s.twoFactorProvider.u2f)return n.errorCode?(console.log(n.errorCode),void u(function(){b(t)},5===n.errorCode?0:1e3)):void e.twoFactor(JSON.stringify(n))},10))}e.state=i,e.twoFactorProviderConstants=s.twoFactorProvider,e.rememberTwoFactor={checked:!1};var w=!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 S=n.get(s.rememberedEmailCookieName);S||e.stateEmail?(e.model={email:e.stateEmail||S,rememberEmail:null!==S},u(function(){$("#masterPassword").focus()})):u(function(){$("#email").focus()});var C,k;e.twoFactorProviders=null,e.twoFactorProvider=null,e.login=function(t){e.loginPromise=a.logIn(t.email,t.masterPassword).then(function(o){if(t.rememberEmail){var r=new Date;r.setFullYear(r.getFullYear()+10),n.put(s.rememberedEmailCookieName,t.email,{expires:r})}else n.remove(s.rememberedEmailCookieName);o&&Object.keys(o).length>0?(C=t.email,k=t.masterPassword,e.twoFactorProviders=f(o),e.twoFactorProvider=g(e.twoFactorProviders),l.eventTrack("Logged In To Two-step"),i.go("frontend.login.twoFactor",{returnState:e.returnState}).then(function(){u(function(){$("#code").focus(),y()})})):(l.eventTrack("Logged In"),v()),t.masterPassword=""})},e.twoFactor=function(t){e.twoFactorProvider!==s.twoFactorProvider.email&&e.twoFactorProvider!==s.twoFactorProvider.authenticator||(t=t.replace(" ","")),e.twoFactorPromise=a.logIn(C,k,t,e.twoFactorProvider,e.rememberTwoFactor.checked||!1),e.twoFactorPromise.then(function(){l.eventTrack("Logged In From Two-step"),v()},function(){e.twoFactorProvider===s.twoFactorProvider.u2f&&y()})},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(),y()})})},e.sendEmail=function(t){if(e.twoFactorProvider===s.twoFactorProvider.email)return r.makeKeyAndHash(C,k).then(function(e){return o.twoFactor.sendEmailLogin({email:C,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(){w=!0})}]),angular.module("bit.accounts").controller("accountsLogoutController",["$scope","authService","$state","$analytics",function(e,t,n,o){t.logOut(),o.eventTrack("Logged Out"),n.go("frontend.login.info")}]),angular.module("bit.accounts").controller("accountsOrganizationAcceptController",["$scope","$state","apiService","authService","toastr","$analytics",function(e,t,n,o,r,a){if(e.state={name:t.current.name,params:t.params},!(t.params.organizationId&&t.params.organizationUserId&&t.params.token&&t.params.email&&t.params.organizationName))return void t.go("frontend.login.info").then(function(){r.error("Invalid parameters.")});e.$on("$viewContentLoaded",function(){o.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(){r.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(){r.error("Unable to accept invitation.","Error")})})):e.loading=!1})}]),angular.module("bit.accounts").controller("accountsPasswordHintController",["$scope","$rootScope","apiService","$analytics",function(e,t,n,o){e.success=!1,e.submit=function(t){e.submitPromise=n.accounts.postPasswordHint({email:t.email},function(){o.eventTrack("Requested Password Hint"),e.success=!0}).$promise}}]),angular.module("bit.accounts").controller("accountsRecoverController",["$scope","apiService","cryptoService","$analytics",function(e,t,n,o){e.success=!1,e.submit=function(r){var a=r.email.toLowerCase();e.submitPromise=n.makeKeyAndHash(r.email,r.masterPassword).then(function(e){return t.twoFactor.recover({email:a,masterPasswordHash:e.hash,recoveryCode:r.code.replace(/\s/g,"").toLowerCase()}).$promise}).then(function(){o.eventTrack("Recovered 2FA"),e.success=!0})}}]),angular.module("bit.accounts").controller("accountsRegisterController",["$scope","$location","apiService","cryptoService","validationService","$analytics","$state","$timeout",function(e,t,n,o,r,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&&(r.addError(t,"MasterPassword","Master password must be at least 8 characters long.",!0),i=!0),e.model.masterPassword!==e.model.confirmMasterPassword&&(r.addError(t,"ConfirmMasterPassword","Master password confirmation does not match.",!0),i=!0),!i){var s,l,c=e.model.email.toLowerCase();e.registerPromise=o.makeKeyAndHash(c,e.model.masterPassword).then(function(e){return s=e,l=o.makeEncKey(e.key),o.makeKeyPair(l.encKey)}).then(function(t){var o={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(o).$promise},function(e){return r.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,o,r){function a(t){for(var n=0;n<r.twoFactorProviderInfo.length;n++)r.twoFactorProviderInfo[n].type===t&&e.providers.push(r.twoFactorProviderInfo[n])}n.eventTrack("accountsTwoFactorMethodsController",{category:"Modal"}),e.providers=[],o.hasOwnProperty(r.twoFactorProvider.authenticator)&&a(r.twoFactorProvider.authenticator),o.hasOwnProperty(r.twoFactorProvider.yubikey)&&a(r.twoFactorProvider.yubikey),o.hasOwnProperty(r.twoFactorProvider.email)&&a(r.twoFactorProvider.email),o.hasOwnProperty(r.twoFactorProvider.duo)&&a(r.twoFactorProvider.duo),o.hasOwnProperty(r.twoFactorProvider.u2f)&&u2f.isSupported&&a(r.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,o,r){if(!t.params.userId||!t.params.token)return void t.go("frontend.login.info").then(function(){o.error("Invalid parameters.")});e.$on("$viewContentLoaded",function(){n.accounts.verifyEmailToken({},{token:t.params.token,userId:t.params.userId},function(){r.eventTrack("Verified Email"),t.go("frontend.login.info",null,{location:"replace"}).then(function(){o.success("Your email has been verified. Thank you.","Success")})},function(){t.go("frontend.login.info",null,{location:"replace"}).then(function(){o.error("Unable to verify email.","Error")})})})}]),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.directives").directive("apiField",function(){var e=function(e,t,n,o){function r(){return o.$setValidity("api",!0),!0}function a(){o.$setValidity("api",!1)}o.$registerApiError=a,o.$validators.apiValidate=r};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){function o(e,o,r){r&&r.then&&(e.$errors=null,e.$loading=!0,r.then(function(t){n(function(){e.$loading=!1})},function(r){n(function(){e.$loading=!1,"string"==typeof r?t.addError(e,null,r,!0):t.addErrors(e,r),o.$broadcast("show-errors-check-validity"),$("html, body").animate({scrollTop:0},200)})}))}return{require:"form",restrict:"A",link:function(e,t,n,r){var a=n.apiForm||null;void 0!==a&&e.$watch(a,o.bind(null,r,e))}}}]),angular.module("bit.directives").directive("letterAvatar",function(){function e(e){var t=0,n=0;for(n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);var o="#";for(n=0;n<3;n++){o+=("00"+(t>>8*n&255).toString(16)).substr(-2)}return o}function t(e,t){var n=e.split(" ");if(n&&n.length>1){for(var o="",r=0;r<t;r++)o+=n[r].substr(0,1);return o}return null}function n(e,t,n){return angular.element("<svg></svg>").attr({xmlns:"http://www.w3.org/2000/svg","pointer-events":"none",width:e,height:t}).css({"background-color":n,width:e+"px",height:t+"px"})}function o(e,t,n,o,r){return angular.element('<text text-anchor="middle"></text>').attr({y:"50%",x:"50%",dy:"0.35em","pointer-events":"auto",fill:t,"font-family":n}).text(e).css({"font-weight":o,"font-size":r+"px"})}return{restrict:"AE",replace:!0,scope:{data:"@"},link:function(r,a,i){function s(){var i=null,s=r.data.toUpperCase();l.charCount>1&&(i=t(s,l.charCount)),i||(i=s.substr(0,l.charCount));var c=o(i,l.textColor,l.fontFamily,l.fontWeight,l.fontSize),u=l.bgColor?l.bgColor:e(s),d=n(l.width,l.height,u);d.append(c);var p=angular.element("<div>").append(d).html(),m=window.btoa(unescape(encodeURIComponent(p))),g="data:image/svg+xml;base64,"+m,f=angular.element("<img>").attr({src:g,title:r.data});"true"===l.round&&f.css("border-radius","50%"),"true"===l.border&&f.css("border",l.borderStyle),l.class&&f.addClass(l.class),"true"===l.dynamic?(a.empty(),a.append(f)):a.replaceWith(f)}var l={charCount:i.charcount||2,data:i.data,textColor:i.textcolor||"#ffffff",bgColor:i.bgcolor,height:i.avheight||45,width:i.avwidth||45,fontSize:i.fontsize||20,fontWeight:i.fontweight||300,fontFamily:i.fontfamily||"Open Sans, HelveticaNeue-Light, Helvetica Neue Light, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif",round:i.round||"true",dynamic:i.dynamic||"true",class:i.avclass||"",border:i.avborder||"false",borderStyle:i.borderstyle||"3px solid white"};"true"===l.dynamic?r.$watch("data",function(){s()}):s()}}}),angular.module("bit.directives").directive("masterPassword",["cryptoService","authService",function(e,t){return{require:"ngModel",restrict:"A",link:function(n,o,r,a){t.getUserProfile().then(function(t){a.$parsers.unshift(function(n){if(n)return e.makeKey(n,t.email).then(function(t){var o=t.keyB64===e.getKey().keyB64;return a.$setValidity("masterPassword",o),o?n:void 0})}),a.$formatters.unshift(function(n){if(n)return e.makeKey(n,t.email).then(function(t){var o=t.keyB64===e.getKey().keyB64;return a.$setValidity("masterPassword",o),n})})})}}}]),angular.module("bit.directives").directive("pageTitle",["$rootScope","$timeout","appSettings",function(e,t,n){return{link:function(n,o){var r=function(e,n,r,a,i){var s="bitwarden Password Manager";n.data&&n.data.pageTitle&&(s=n.data.pageTitle+" - bitwarden Password Manager"),t(function(){o.text(s)})};e.$on("$stateChangeStart",r)}}}]),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,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))},n=function(e){switch(Math.round(e/33)){case 0:case 1:return"danger";case 2:return"warning";case 3:return"success"}},o=function(e){e.value=t(e.username,e.password),e.valueClass=n(e.value)};e.$watch("password",function(){o(e)}),e.$watch("username",function(){o(e)})}}}),angular.module("bit.directives").directive("passwordViewer",function(){return{restrict:"A",link:function(e,t,n){var o=n.passwordViewer;o&&(t.onclick=function(e){},t.on("click",function(e){var n=$(o);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 o=null,r=function(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",n=function(e,t,n){return t+1>=e.length&&(e=Array(t+1-e.length).join(n)+e),e},o=function(e){return(e<15.5?"0":"")+Math.round(e).toString(16)},r=function(e){return parseInt(e,16)},a=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},i=function(e){for(var t=new Uint8Array(e),n=[],o=0;o<t.length;o++)n.push((t[o]>>>4).toString(16)),n.push((15&t[o]).toString(16));return n.join("")},s=function(t){t=t.toUpperCase();var o,r="";for(o=0;o<t.length;o++)e.indexOf(t[o])<0||(r+=t[o]);t=r;var a="",i="";for(o=0;o<t.length;o++){var s=e.indexOf(t.charAt(o));s<0||(a+=n(s.toString(2),5,"0"))}for(o=0;o+4<=a.length;o+=4){var l=a.substr(o,4);i+=parseInt(l,2).toString(16)}return i},l=function(e){return a(s(e))},c=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 i(e)}).catch(function(e){return null})};this.getCode=function(e){var i=Math.round((new Date).getTime()/1e3),s=n(o(Math.floor(i/30)),16,"0"),u=a(s),d=l(e);return d.length&&u.length?c(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=new r,i=function(t){a.getCode(t.key).then(function(n){e(function(){
n?(t.codeFormatted=n.substring(0,3)+" "+n.substring(3),t.code=n):(t.code=null,o&&clearInterval(o))})})},s=function(t){e(function(){var e=Math.round((new Date).getTime()/1e3),n=e%30,o=30-n;t.sec=o,t.dash=(2.62*n).toFixed(2),t.low=o<=7,0===n&&i(t)})};n.$watch("key",function(){if(!n.key)return n.code=null,void(o&&clearInterval(o));i(n),s(n),o&&clearInterval(o),o=setInterval(function(){s(n)},1e3)}),n.$on("$destroy",function(){o&&clearInterval(o)}),n.clipboardError=function(e){alert("Your web browser does not support easy clipboard copying.")}}}}]),angular.module("bit.global").controller("appsController",["$scope","$state",function(e,t){}]),angular.module("bit.global").controller("mainController",["$scope","$state","authService","appSettings","toastr","$window","$document","cryptoService","$uibModal","apiService",function(e,t,n,o,r,a,i,s,l,c){var u=this;u.bodyClass="",u.usingControlSidebar=u.openControlSidebar=!1,u.searchVaultText=null,u.version=o.version,u.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){u.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,o,r){if(u.usingEncKey=!!s.getEncKey(),u.searchVaultText=null,t.data.bodyClass)return void(u.bodyClass=t.data.bodyClass);u.bodyClass="",u.usingControlSidebar=!!t.data.controlSidebar,u.openControlSidebar=u.usingControlSidebar&&i.width()>768}),e.addLogin=function(){e.$broadcast("vaultAddLogin")},e.addFolder=function(){e.$broadcast("vaultAddFolder")},e.addOrganizationLogin=function(){e.$broadcast("organizationVaultAddLogin")},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(){r.success("Verification email sent."),e.sendingVerify=!1,e.verifyEmailSent=!0}).catch(function(){r.success("Verification email failed."),e.sendingVerify=!1}))},e.updateBrowser=function(){a.open("https://browser-update.org/update.html","_blank")};var d,p,m,g={scrollbarWidth:function(){if(!d){var e=$("body");e.addClass("bit-position-body-scrollbar-measure"),d=a.innerWidth-e[0].clientWidth,d=isFinite(d)?d:0,e.removeClass("bit-position-body-scrollbar-measure")}return d},scrollbarInfo:function(){return{width:g.scrollbarWidth(),visible:i.height()>$(a).height()}}};$(window).on("show.bs.dropdown",function(e){var t=m=$(e.target),n=t.data("appendTo");if(!n)return!0;p=t.find(".dropdown-menu"),$(n).append(p.detach());var o=t.offset(),r={display:"block",top:o.top+t.outerHeight()-("body"!==n?$(window).scrollTop():0)};if(p.hasClass("dropdown-menu-right")){var i=g.scrollbarInfo(),s=0;i.visible&&i.width&&(s=i.width),r.right=a.innerWidth-s-(o.left+t.prop("offsetWidth"))+"px",r.left="auto"}else r.left=o.left+"px",r.right="auto";p.css(r)}),$(window).on("hide.bs.dropdown",function(e){if(!p)return!0;$(e.target).append(p.detach()),p.hide(),p=null,m=null}),e.$on("removeAppendedDropdownMenu",function(e,t){if(!p&&!m)return!0;m.append(p.detach()),p.hide(),p=null,m=null})}]),angular.module("bit.global").controller("paidOrgRequiredController",["$scope","$state","$uibModalInstance","$analytics","$uibModalStack","orgId","constants","authService",function(e,t,n,o,r,a,i,s){o.eventTrack("paidOrgRequiredController",{category:"Modal"}),s.getUserProfile().then(function(t){e.admin=t.organizations[a].type!==i.orgUserType.user}),e.go=function(){e.admin&&(o.eventTrack("Get Paid Org"),t.go("backend.org.billing",{orgId:a}).then(function(){r.dismissAll()}))},e.close=function(){n.dismiss("close")}}]),angular.module("bit.global").controller("premiumRequiredController",["$scope","$state","$uibModalInstance","$analytics","$uibModalStack",function(e,t,n,o,r){o.eventTrack("premiumRequiredController",{category:"Modal"}),e.go=function(){o.eventTrack("Get Premium"),t.go("backend.user.settingsPremium").then(function(){r.dismissAll()})},e.close=function(){n.dismiss("close")}}]),angular.module("bit.global").controller("sideNavController",["$scope","$state","authService","toastr","$analytics","constants",function(e,t,n,o,r,a){e.$state=t,e.params=t.params,e.orgs=[],e.name="",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 o=[];for(var r in n.organizations)n.organizations.hasOwnProperty(r)&&(n.organizations[r].enabled||n.organizations[r].type<2)&&o.push(n.organizations[r]);e.orgs=o}}),e.viewOrganization=function(e){if(e.type===a.orgUserType.user)return void o.error("You cannot manage this organization.");r.eventTrack("View Organization From Side Nav"),t.go("backend.org.dashboard",{orgId:e.id})},e.searchVault=function(){t.go("backend.user.vault")},e.searchOrganizationVault=function(){t.go("backend.org.vault",{orgId:t.params.orgId})},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.organization").controller("organizationBillingAdjustSeatsController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,o,r,a,i){r.eventTrack("organizationBillingAdjustSeatsController",{category:"Modal"}),e.add=i,e.seatAdjustment=0,e.submit=function(){var s={seatAdjustment:e.seatAdjustment};i||(s.seatAdjustment*=-1),e.submitPromise=o.organizations.putSeat({id:t.params.orgId},s).$promise.then(function(t){i?(r.eventTrack("Added Seats"),a.success("You have added "+e.seatAdjustment+" seats.")):(r.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,o,r,a,i){r.eventTrack("organizationBillingAdjustStorageController",{category:"Modal"}),e.add=i,e.storageAdjustment=0,e.submit=function(){var s={storageGbAdjustment:e.storageAdjustment};i||(s.storageGbAdjustment*=-1),e.submitPromise=o.organizations.putStorage({id:t.params.orgId},s).$promise.then(function(t){i?(r.eventTrack("Added Organization Storage"),a.success("You have added "+e.storageAdjustment+" GB.")):(r.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","stripe","$analytics","toastr","existingPaymentMethod",function(e,t,n,o,r,a,i,s){a.eventTrack("organizationBillingChangePaymentController",{category:"Modal"}),e.existingPaymentMethod=s,e.paymentMethod="card",e.showPaymentOptions=!1,e.card={},e.submit=function(){e.submitPromise=r.card.createToken(e.card).then(function(e){var n={paymentToken:e.id};return o.organizations.putPayment({id:t.params.orgId},n).$promise},function(e){throw e.message}).then(function(t){e.card=null,s?(a.eventTrack("Changed Organization Payment Method"),i.success("You have changed your payment method.")):(a.eventTrack("Added Organization Payment Method"),i.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,o,r,a){a.eventTrack("organizationBillingChangePlanController",{category:"Modal"}),e.submit=function(){},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationBillingController",["$scope","apiService","$state","$uibModal","toastr","$analytics",function(e,t,n,o,r,a){function i(){t.organizations.getBilling({id:n.params.orgId},function(t){e.loading=!1,e.noSubscription=0===t.PlanType;var n=0;if(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});var o=[];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.charges=[],e.paymentSource=null,e.plan=null,e.subscription=null,e.loading=!0,e.$on("$viewContentLoaded",function(){i()}),e.changePayment=function(){o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingChangePayment.html",controller:"organizationBillingChangePaymentController",resolve:{existingPaymentMethod:function(){return e.paymentSource?e.paymentSource.description:null}}}).result.then(function(){i()})},e.changePlan=function(){o.open({animation:!0,templateUrl:"app/organization/views/organizationBillingChangePlan.html",controller:"organizationBillingChangePlanController",resolve:{plan:function(){return e.plan}}}).result.then(function(){i()})},e.adjustSeats=function(e){o.open({animation:!0,templateUrl:"app/organization/views/organizationBillingAdjustSeats.html",controller:"organizationBillingAdjustSeatsController",resolve:{add:function(){return e}}}).result.then(function(){i()})},e.adjustStorage=function(e){o.open({animation:!0,templateUrl:"app/settings/views/settingsBillingAdjustStorage.html",controller:"organizationBillingAdjustStorageController",resolve:{add:function(){return e}}}).result.then(function(){i()})},e.cancel=function(){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"),r.success("Organization subscription has been canceled."),i()})},e.reinstate=function(){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"),r.success("Organization cancellation request has been removed."),i()})}}]),angular.module("bit.organization").controller("organizationCollectionsAddController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics","authService",function(e,t,n,o,r,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 r=n.organizations[t.params.orgId];e.useGroups=!!r.useGroups}return e.useGroups?o.groups.listOrganization({orgId:t.params.orgId}).$promise:null}).then(function(t){if(!t)return void(e.loading=!1);for(var n=[],o=0;o<t.Data.length;o++)n.push({id:t.Data[o].Id,name:t.Data[o].Name,accessAll:t.Data[o].AccessAll}),t.Data[o].AccessAll||s++;e.groups=n,e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.groups.length;o++)n[e.groups[o].id]={id:e.groups[o].id,readOnly:e.groups[o].id in e.selectedGroups&&e.selectedGroups[e.groups[o].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=r.encryptCollection(i,t.params.orgId);if(e.useGroups){s.groups=[];for(var l in 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=o.collections.post({orgId:t.params.orgId},s,function(e){a.eventTrack("Created Collection");var o=r.decryptCollection(e,t.params.orgId,!0);n.close(o)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationCollectionsController",["$scope","$state","apiService","$uibModal","cipherService","$filter","toastr","$analytics",function(e,t,n,o,r,a,i,s){function l(){n.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1})}e.collections=[],e.loading=!0,e.$on("$viewContentLoaded",function(){l()}),e.$on("organizationCollectionsAdd",function(t,n){e.add()}),e.add=function(){o.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsAdd.html",controller:"organizationCollectionsAddController"}).result.then(function(t){e.collections.push(t)})},e.edit=function(t){o.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){o.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){o.open({animation:!0,templateUrl:"app/organization/views/organizationCollectionsGroups.html",controller:"organizationCollectionsGroupsController",resolve:{collection:function(){return e}}}).result.then(function(){})},e.delete=function(o){confirm("Are you sure you want to delete this collection ("+o.name+")?")&&n.collections.del({orgId:t.params.orgId,id:o.id},function(){var t=e.collections.indexOf(o);t>-1&&e.collections.splice(t,1),s.eventTrack("Deleted Collection"),i.success(o.name+" has been deleted.","Collection Deleted")},function(){i.error(o.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,o,r,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 o.collections.getDetails({orgId:t.params.orgId,id:i}).$promise}).then(function(t){e.collection=r.decryptCollection(t);var n={};if(t.Groups)for(var o=0;o<t.Groups.length;o++)n[t.Groups[o].Id]={id:t.Groups[o].Id,readOnly:t.Groups[o].ReadOnly};return e.selectedGroups=n,s.getUserProfile()}).then(function(n){if(n.organizations){var r=n.organizations[t.params.orgId];e.useGroups=!!r.useGroups}return e.useGroups?o.groups.listOrganization({orgId:t.params.orgId}).$promise:null}).then(function(t){if(!t)return void(e.loading=!1);for(var n=[],o=0;o<t.Data.length;o++)n.push({id:t.Data[o].Id,name:t.Data[o].Name,accessAll:t.Data[o].AccessAll}),t.Data[o].AccessAll||l++;e.groups=n,e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.groups.length;o++)n[e.groups[o].id]={id:e.groups[o].id,readOnly:e.groups[o].id in e.selectedGroups&&e.selectedGroups[e.groups[o].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=r.encryptCollection(s,t.params.orgId);if(e.useGroups){l.groups=[];for(var c in 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=o.collections.put({orgId:t.params.orgId,id:i},l,function(e){a.eventTrack("Edited Collection");var o=r.decryptCollection(e,t.params.orgId,!0);n.close(o)}).$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,o,r,a,i,s){a.eventTrack("organizationCollectionsUsersController",{category:"Modal"}),e.loading=!0,e.collection=i,e.users=[],n.opened.then(function(){e.loading=!1,o.collections.listUsers({orgId:t.params.orgId,id:i.id},function(t){if(t&&t.Data.length){for(var n=[],o=0;o<t.Data.length;o++)n.push({organizationUserId:t.Data[o].OrganizationUserId,name:t.Data[o].Name,email:t.Data[o].Email,type:t.Data[o].Type,status:t.Data[o].Status,readOnly:t.Data[o].ReadOnly,accessAll:t.Data[o].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+")?")&&o.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",function(e,t,n){e.$on("$viewContentLoaded",function(){t.getUserProfile().then(function(t){t.organizations&&(e.orgProfile=t.organizations[n.params.orgId])})})}]),angular.module("bit.organization").controller("organizationDeleteController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics",function(e,t,n,o,r,a,i,s){s.eventTrack("organizationDeleteController",{category:"Modal"}),e.submit=function(){e.submitPromise=r.hashPassword(e.masterPassword).then(function(e){return n.organizations.del({id:t.params.orgId},{masterPasswordHash:e}).$promise}).then(function(){return o.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(){o.dismiss("cancel")}}]),angular.module("bit.organization").controller("organizationGroupsAddController",["$scope","$state","$uibModalInstance","apiService","cipherService","$analytics",function(e,t,n,o,r,a){a.eventTrack("organizationGroupsAddController",{category:"Modal"}),e.collections=[],e.selectedCollections={},e.loading=!0,n.opened.then(function(){return o.collections.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].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(r){var i={name:r.name,accessAll:!!r.accessAll,externalId:r.externalId};if(!i.accessAll){i.collections=[];for(var s in e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&i.collections.push(e.selectedCollections[s])}e.submitPromise=o.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",function(e,t,n,o,r,a,i){function s(){n.groups.listOrganization({orgId:t.params.orgId},function(t){for(var n=[],o=0;o<t.Data.length;o++)n.push({id:t.Data[o].Id,name:t.Data[o].Name});e.groups=n,e.loading=!1})}e.groups=[],e.loading=!0,e.$on("$viewContentLoaded",function(){s()}),e.$on("organizationGroupsAdd",function(t,n){e.add()}),e.add=function(){o.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsAdd.html",controller:"organizationGroupsAddController"}).result.then(function(t){e.groups.push(t)})},e.edit=function(t){o.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsEdit.html",controller:"organizationGroupsEditController",resolve:{id:function(){return t.id}}}).result.then(function(t){var n=r("filter")(e.groups,{id:t.id},!0);n&&n.length>0&&(n[0].name=t.name)})},e.users=function(e){o.open({animation:!0,templateUrl:"app/organization/views/organizationGroupsUsers.html",controller:"organizationGroupsUsersController",size:"lg",resolve:{group:function(){return e}}}).result.then(function(){})},e.delete=function(o){confirm("Are you sure you want to delete this group ("+o.name+")?")&&n.groups.del({orgId:t.params.orgId,id:o.id},function(){var t=e.groups.indexOf(o);t>-1&&e.groups.splice(t,1),i.eventTrack("Deleted Group"),a.success(o.name+" has been deleted.","Group Deleted")},function(){a.error(o.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,o,r,a,i){a.eventTrack("organizationGroupsEditController",{category:"Modal"}),e.collections=[],e.selectedCollections={},e.loading=!0,n.opened.then(function(){return o.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 r={};if(n.Collections)for(var a=0;a<n.Collections.length;a++)r[n.Collections[a].Id]={id:n.Collections[a].Id,readOnly:n.Collections[a].ReadOnly};return e.selectedCollections=r,o.collections.listOrganization({orgId:t.params.orgId}).$promise}).then(function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].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 r={name:e.group.name,accessAll:!!e.group.accessAll,externalId:e.group.externalId};if(!r.accessAll){r.collections=[];for(var s in e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&r.collections.push(e.selectedCollections[s])}e.submitPromise=o.groups.put({orgId:t.params.orgId,id:i},r,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,o,r,a,i){r.eventTrack("organizationGroupUsersController",{category:"Modal"}),e.loading=!0,e.group=a,e.users=[],n.opened.then(function(){return o.groups.listUsers({orgId:t.params.orgId,id:a.id}).$promise}).then(function(t){var n=[];if(t&&t.Data.length)for(var o=0;o<t.Data.length;o++)n.push({organizationUserId:t.Data[o].OrganizationUserId,name:t.Data[o].Name,email:t.Data[o].Email,type:t.Data[o].Type,status:t.Data[o].Status,accessAll:t.Data[o].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+")?")&&o.groups.delUser({orgId:t.params.orgId,id:a.id,orgUserId:n.organizationUserId},null,function(){i.success(n.email+" has been removed.","User Removed"),r.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",function(e,t,n,o,r,a,i,s){function l(){r.organizationUsers.list({orgId:t.params.orgId},function(t){for(var n=[],o=0;o<t.Data.length;o++){var r={id:t.Data[o].Id,userId:t.Data[o].UserId,name:t.Data[o].Name,email:t.Data[o].Email,status:t.Data[o].Status,type:t.Data[o].Type,accessAll:t.Data[o].AccessAll};n.push(r)}e.users=n})}e.users=[],e.useGroups=!1,e.$on("$viewContentLoaded",function(){l(),a.getUserProfile().then(function(n){if(n.organizations){var o=n.organizations[t.params.orgId];e.useGroups=!!o.useGroups}})}),e.reinvite=function(e){r.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+")?")&&r.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){r.users.getPublicKey({id:e.userId},function(n){var a=o.getOrgKey(t.params.orgId);if(!a)return void i.error("Unable to confirm user.","Error");var l=o.rsaEncrypt(a.key,n.PublicKey);r.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")})},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(){l()})},e.edit=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleEdit.html",controller:"organizationPeopleEditController",resolve:{orgUser:function(){return e}}}).result.then(function(){l()})},e.groups=function(e){n.open({animation:!0,templateUrl:"app/organization/views/organizationPeopleGroups.html",controller:"organizationPeopleGroupsController",resolve:{orgUser:function(){return e}}}).result.then(function(){})}}]),angular.module("bit.organization").controller("organizationPeopleEditController",["$scope","$state","$uibModalInstance","apiService","cipherService","orgUser","$analytics",function(e,t,n,o,r,a,i){i.eventTrack("organizationPeopleEditController",{category:"Modal"}),e.loading=!0,e.collections=[],e.selectedCollections={},n.opened.then(function(){o.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1}),o.organizationUsers.get({orgId:t.params.orgId,id:a.id},function(t){var n={};if(t&&t.Collections)for(var o=0;o<t.Collections.length;o++)n[t.Collections[o].Id]={id:t.Collections[o].Id,readOnly:t.Collections[o].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 o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].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(r){var s=[];if(!e.accessAll)for(var l in e.selectedCollections)e.selectedCollections.hasOwnProperty(l)&&s.push(e.selectedCollections[l]);e.submitPromise=o.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("organizationPeopleGroupsController",["$scope","$state","$uibModalInstance","apiService","orgUser","$analytics",function(e,t,n,o,r,a){a.eventTrack("organizationPeopleGroupsController",{category:"Modal"}),e.loading=!0,e.groups=[],e.selectedGroups={},e.orgUser=r,n.opened.then(function(){return o.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,o.organizationUsers.listGroups({orgId:t.params.orgId,id:r.id}).$promise}).then(function(t){var n={};if(t)for(var o=0;o<t.length;o++)n[t[o]]=!0;e.selectedGroups=n,e.loading=!1}),e.toggleGroupSelectionAll=function(t){var n={}
;if(t.target.checked)for(var o=0;o<e.groups.length;o++)n[e.groups[o].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=o.organizationUsers.putGroups({orgId:t.params.orgId,id:r.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,o,r,a){a.eventTrack("organizationPeopleInviteController",{category:"Modal"}),e.loading=!0,e.collections=[],e.selectedCollections={},e.model={type:"User"},n.opened.then(function(){o.collections.listOrganization({orgId:t.params.orgId},function(n){e.collections=r.decryptCollections(n.Data,t.params.orgId,!0),e.loading=!1})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].id]={id:e.collections[o].id,readOnly:e.collections[o].id in e.selectedCollections&&e.selectedCollections[e.collections[o].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(r){var i=[];if(!r.accessAll)for(var s in e.selectedCollections)e.selectedCollections.hasOwnProperty(s)&&i.push(e.selectedCollections[s]);var l=r.emails.trim().split(/\s*,\s*/);e.submitPromise=o.organizationUsers.invite({orgId:t.params.orgId},{emails:l,type:r.type,collections:i,accessAll:r.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",function(e,t,n,o,r,a,i){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}})}),e.generalSave=function(){e.generalPromise=n.organizations.put({id:t.params.orgId},e.model,function(e){r.updateProfileOrganization(e).then(function(e){i.eventTrack("Updated Organization Settings"),o.success("Organization has been updated.","Success!")})}).$promise},e.delete=function(){a.open({animation:!0,templateUrl:"app/organization/views/organizationDelete.html",controller:"organizationDeleteController"})}}]),angular.module("bit.organization").controller("organizationVaultAddLoginController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","$analytics","authService","orgId","$uibModal",function(e,t,n,o,r,a,i,s,l,c){function u(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}i.eventTrack("organizationVaultAddLoginController",{category:"Modal"}),e.login={},e.hideFolders=e.hideFavorite=e.fromOrg=!0,s.getUserProfile().then(function(t){var n=t.organizations[l];e.useTotp=n.useTotp}),e.savePromise=null,e.save=function(o){o.organizationId=l;var a=r.encryptLogin(o);e.savePromise=t.logins.postAdmin(a,function(e){i.eventTrack("Created Organization Login");var t=r.decryptLogin(e);n.close(t)}).$promise},e.generatePassword=function(){e.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(i.eventTrack("Generated Password From Add"),e.login.password=a.generatePassword({length:12,special:!0}))},e.clipboardSuccess=function(e){e.clearSelection(),u(e)},e.clipboardError=function(e,t){t&&u(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","loginId","$analytics","validationService","toastr","$timeout",function(e,t,n,o,r,a,i,s,l,c){i.eventTrack("organizationVaultAttachmentsController",{category:"Modal"}),e.login={},e.loading=!0,e.isPremium=!0,e.canUseAttachments=!0;var u=!1;t.logins.getAdmin({id:a},function(t){e.login=r.decryptLogin(t),e.loading=!1},function(){e.loading=!1}),e.save=function(c){var d=document.getElementById("file").files;if(!d||!d.length)return void s.addError(c,"file","Select a file.",!0);var p=o.getOrgKey(e.login.organizationId);e.savePromise=r.encryptAttachmentFile(p,d[0]).then(function(e){var n=new FormData,o=new Blob([e.data],{type:"application/octet-stream"});return n.append("data",o,e.fileName),t.ciphers.postAttachment({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){e?s.addError(c,"file",e,!0):s.addError(c,"file","Something went wrong.",!0)})},e.download=function(t){t.loading=!0;var n=o.getOrgKey(e.login.organizationId);r.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.delAttachment({id:a,attachmentId:n.id}).$promise.then(function(){n.loading=!1,i.eventTrack("Deleted Organization Attachment");var t=e.login.attachments.indexOf(n);t>-1&&e.login.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,o,r){u||(t.preventDefault(),u=!0,n.close(!!e.login.attachments&&e.login.attachments.length>0))})}]),angular.module("bit.organization").controller("organizationVaultController",["$scope","apiService","cipherService","$analytics","$q","$state","$localStorage","$uibModal","$filter","authService",function(e,t,n,o,r,a,i,s,l,c){e.logins=[],e.collections=[],e.loading=!0,e.$on("$viewContentLoaded",function(){var o=t.collections.listOrganization({orgId:a.params.orgId},function(t){for(var o=([{id:null,name:"Unassigned",collapsed:i.collapsedOrgCollections&&"unassigned"in i.collapsedOrgCollections}]),r=0;r<t.Data.length;r++){var a=n.decryptCollection(t.Data[r],null,!0);a.collapsed=i.collapsedOrgCollections&&a.id in i.collapsedOrgCollections,o.push(a)}e.collections=o}).$promise,s=t.ciphers.listOrganizationDetails({organizationId:a.params.orgId},function(t){for(var o=[],r=0;r<t.Data.length;r++)if(1===t.Data[r].Type){var a=n.decryptLoginPreview(t.Data[r]);o.push(a)}e.logins=o}).$promise;r.all([o,s]).then(function(){e.loading=!1})}),e.filterByCollection=function(e){return function(t){return t.collectionIds&&t.collectionIds.length?t.collectionIds.indexOf(e.id)>-1:null===e.id}},e.collectionSort=function(e){return e.id?e.name.toLowerCase():""},e.collapseExpand=function(e){i.collapsedOrgCollections||(i.collapsedOrgCollections={});var t=e.id||"unassigned";t in i.collapsedOrgCollections?delete i.collapsedOrgCollections[t]:i.collapsedOrgCollections[t]=!0},e.editLogin=function(t){s.open({animation:!0,templateUrl:"app/vault/views/vaultEditLogin.html",controller:"organizationVaultEditLoginController",resolve:{loginId:function(){return t.id},orgId:function(){return a.params.orgId}}}).result.then(function(n){if("edit"===n.action)t.name=n.data.name,t.username=n.data.username;else if("delete"===n.action){var o=e.logins.indexOf(t);o>-1&&e.logins.splice(o,1)}})},e.$on("organizationVaultAddLogin",function(t,n){e.addLogin()}),e.addLogin=function(){s.open({animation:!0,templateUrl:"app/vault/views/vaultAddLogin.html",controller:"organizationVaultAddLoginController",resolve:{orgId:function(){return a.params.orgId}}}).result.then(function(t){e.logins.push(t)})},e.editCollections=function(t){s.open({animation:!0,templateUrl:"app/organization/views/organizationVaultLoginCollections.html",controller:"organizationVaultLoginCollectionsController",resolve:{cipher:function(){return t},collections:function(){return e.collections}}}).result.then(function(e){e.collectionIds&&(t.collectionIds=e.collectionIds)})},e.attachments=function(e){c.getUserProfile().then(function(t){return!!t.organizations[e.organizationId].maxStorageGb}).then(function(t){if(!t)return void s.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return e.organizationId}}});s.open({animation:!0,templateUrl:"app/vault/views/vaultAttachments.html",controller:"organizationVaultAttachmentsController",resolve:{loginId:function(){return e.id}}}).result.then(function(t){e.hasAttachments=t})})},e.removeLogin=function(e,n){if(confirm("Are you sure you want to remove this login ("+e.name+") from the collection ("+n.name+") ?")){for(var r={collectionIds:[]},a=0;a<e.collectionIds.length;a++)e.collectionIds[a]!==n.id&&r.collectionIds.push(e.collectionIds[a]);t.ciphers.putCollections({id:e.id},r).$promise.then(function(t){o.eventTrack("Removed Login From Collection"),e.collectionIds=r.collectionIds})}},e.deleteLogin=function(n){confirm("Are you sure you want to delete this login ("+n.name+")?")&&t.ciphers.delAdmin({id:n.id},function(){o.eventTrack("Deleted Login");var t=e.logins.indexOf(n);t>-1&&e.logins.splice(t,1)})}}]),angular.module("bit.organization").controller("organizationVaultEditLoginController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","loginId","$analytics","orgId","$uibModal",function(e,t,n,o,r,a,i,s,l,c){function u(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("organizationVaultEditLoginController",{category:"Modal"}),e.login={},e.hideFolders=e.hideFavorite=e.fromOrg=!0,t.logins.getAdmin({id:i},function(t){e.login=r.decryptLogin(t),e.useTotp=e.login.organizationUseTotp}),e.save=function(o){var a=r.encryptLogin(o);e.savePromise=t.logins.putAdmin({id:i},a,function(e){s.eventTrack("Edited Organization Login");var t=r.decryptLogin(e);n.close({action:"edit",data:t})}).$promise},e.generatePassword=function(){e.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Edit"),e.login.password=a.generatePassword({length:12,special:!0}))},e.clipboardSuccess=function(e){e.clearSelection(),u(e)},e.clipboardError=function(e,t){t&&u(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 login ("+e.login.name+")?")&&t.ciphers.delAdmin({id:e.login.id},function(){s.eventTrack("Deleted Organization Login From Edit"),n.close({action:"delete",data:e.login.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.organization").controller("organizationVaultLoginCollectionsController",["$scope","apiService","$uibModalInstance","cipherService","cipher","$analytics","collections",function(e,t,n,o,r,a,i){a.eventTrack("organizationVaultLoginCollectionsController",{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=r;var o={};if(e.cipher.collectionIds)for(n=0;n<e.cipher.collectionIds.length;n++)o[e.cipher.collectionIds[n]]=!0;e.selectedCollections=o}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].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 o={collectionIds:[]};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&o.collectionIds.push(i);e.submitPromise=t.ciphers.putCollectionsAdmin({id:r.id},o).$promise.then(function(e){a.eventTrack("Edited Login Collections"),n.close({action:"collectionsEdit",collectionIds:o.collectionIds})})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.tools").controller("reportsBreachController",["$scope","apiService","toastr","authService",function(e,t,n,o){e.loading=!0,e.error=!1,e.breachAccounts=[],e.email=null,e.$on("$viewContentLoaded",function(){o.getUserProfile().then(function(n){return e.email=n.email,t.hibp.get({email:e.email}).$promise}).then(function(t){for(var n=[],o=0;o<t.length;o++){var r={id:t[o].Name,title:t[o].Title,domain:t[o].Domain,date:new Date(t[o].BreachDate),reportedDate:new Date(t[o].AddedDate),modifiedDate:new Date(t[o].ModifiedDate),count:t[o].PwnCount,description:t[o].Description,classes:t[o].DataClasses,image:"https://haveibeenpwned.com/Content/Images/PwnedLogos/"+t[o].Name+"."+t[o].LogoType};n.push(r)}e.breachAccounts=n,e.loading=!1},function(t){e.error=404!==t.status,e.loading=!1})})}]),angular.module("bit.vault").controller("settingsAddEditEquivalentDomainController",["$scope","$uibModalInstance","$analytics","domainIndex","domains",function(e,t,n,o,r){n.eventTrack("settingsAddEditEquivalentDomainController",{category:"Modal"}),e.domains=r,e.index=o,e.submit=function(r){n.eventTrack((o?"Edited":"Added")+" Equivalent Domain"),t.close({domains:e.domains,index:o})},e.close=function(){t.dismiss("close")}}]),angular.module("bit.settings").controller("settingsBillingAdjustStorageController",["$scope","$state","$uibModalInstance","apiService","$analytics","toastr","add",function(e,t,n,o,r,a,i){r.eventTrack("settingsBillingAdjustStorageController",{category:"Modal"}),e.add=i,e.storageAdjustment=0,e.submit=function(){var t={storageGbAdjustment:e.storageAdjustment};i||(t.storageGbAdjustment*=-1),e.submitPromise=o.accounts.putStorage(null,t).$promise.then(function(t){i?(r.eventTrack("Added Storage"),a.success("You have added "+e.storageAdjustment+" GB.")):(r.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","stripe","$analytics","toastr","existingPaymentMethod","appSettings","$timeout",function(e,t,n,o,r,a,i,s,l,c){function u(t){return"paypal"===e.paymentMethod?d.requestPaymentMethod().then(function(e){return e.nonce}).catch(function(e){throw e.message}):r.card.createToken(t).then(function(e){return e.id}).catch(function(e){throw e.message})}a.eventTrack("settingsBillingChangePaymentController",{category:"Modal"}),e.existingPaymentMethod=s,e.paymentMethod="card",e.dropinLoaded=!1,e.showPaymentOptions=!1,e.card={};var d=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){if(t)return void console.error(t);d=n,c(function(){e.dropinLoaded=!0})})},e.submit=function(){e.submitPromise=u(e.card).then(function(e){if(!e)throw"No payment token.";var t={paymentToken:e};return o.accounts.putPayment(null,t).$promise},function(e){throw e}).then(function(t){e.card=null,s?(a.eventTrack("Changed Payment Method"),i.success("You have changed your payment method.")):(a.eventTrack("Added Payment Method"),i.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",function(e,t,n,o,r,a,i){function s(){n.getUserProfile().then(function(n){return e.premium=n.premium,n.premium?t.accounts.getBilling({}).$promise:null}).then(function(t){if(!t)return o.go("backend.user.settingsPremium");var n=0;if(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 r=[];if(t&&t.Charges)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.loading=!1})}e.charges=[],e.paymentSource=null,e.subscription=null,e.loading=!0,e.$on("$viewContentLoaded",function(){s()}),e.changePayment=function(){r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingChangePayment.html",controller:"settingsBillingChangePaymentController",resolve:{existingPaymentMethod:function(){return e.paymentSource?e.paymentSource.description:null}}}).result.then(function(){s()})},e.adjustStorage=function(e){r.open({animation:!0,templateUrl:"app/settings/views/settingsBillingAdjustStorage.html",controller:"settingsBillingAdjustStorageController",resolve:{add:function(){return e}}}).result.then(function(){s()})},e.cancel=function(){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."),s()})},e.reinstate=function(){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."),s()})}}]),angular.module("bit.settings").controller("settingsChangeEmailController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","validationService",function(e,t,n,o,r,a,i,s,l){s.eventTrack("settingsChangeEmailController",{category:"Modal"});var c,u,d;e.token=function(t,o){if(!r.getEncKey())return void l.addError(o,null,"You cannot change your email until you update your encryption key.",!0);u=t.masterPassword,d=t.newEmail.toLowerCase(),e.tokenPromise=r.hashPassword(u).then(function(t){c=t;var o={newEmail:d,masterPasswordHash:c};return n.accounts.emailToken(o,function(){e.tokenSent=!0}).$promise})},e.confirm=function(l){e.confirmPromise=r.makeKeyAndHash(d,u).then(function(e){var t=r.getEncKey(),o=r.encrypt(t.key,e.key,"raw"),a={token:l.token,newEmail:d,masterPasswordHash:c,newMasterPasswordHash:e.hash,key:o};return n.accounts.email(a).$promise}).then(function(){return o.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(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsChangePasswordController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","validationService","toastr","$analytics",function(e,t,n,o,r,a,i,s,l){l.eventTrack("settingsChangePasswordController",{category:"Modal"}),e.save=function(c,u){var d=!1;if(r.getEncKey()||(i.addError(u,null,"You cannot change your master password until you update your encryption key.",!0),d=!0),e.model.newMasterPassword.length<8&&(i.addError(u,"NewMasterPasswordHash","Master password must be at least 8 characters long.",!0),d=!0),e.model.newMasterPassword!==e.model.confirmNewMasterPassword&&(i.addError(u,"ConfirmNewMasterPasswordHash","New master password confirmation does not match.",!0),d=!0),!d){var p;e.savePromise=a.getUserProfile().then(function(e){return r.makeKeyAndHash(e.email,c.newMasterPassword)}).then(function(e){return p=e,r.hashPassword(c.masterPassword)}).then(function(e){var t=r.getEncKey(),o=r.encrypt(t.key,p.key,"raw"),a={masterPasswordHash:e,newMasterPasswordHash:p.hash,key:o};return n.accounts.putPassword(a).$promise}).then(function(){return o.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(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsController",["$scope","$state","$uibModal","apiService","toastr","authService",function(e,t,n,o,r,a){function i(){$("html, body").animate({scrollTop:0},200)}e.model={profile:{},twoFactorEnabled:!1,email:null},e.$on("$viewContentLoaded",function(){o.accounts.getProfile({},function(t){if(e.model={profile:{name:t.Name,masterPasswordHint:t.MasterPasswordHint,culture:t.Culture},email:t.Email,twoFactorEnabled:t.TwoFactorEnabled},t.Organizations){for(var n=[],o=0;o<t.Organizations.length;o++)2===t.Organizations[o].Status&&n.push({id:t.Organizations[o].Id,name:t.Organizations[o].Name,status:t.Organizations[o].Status,type:t.Organizations[o].Type,enabled:t.Organizations[o].Enabled});e.model.organizations=n}})}),e.generalSave=function(){e.generalPromise=o.accounts.putProfile({},e.model.profile,function(e){a.setUserProfile(e).then(function(e){r.success("Account has been updated.","Success!")})}).$promise},e.passwordHintSave=function(){e.passwordHintPromise=o.accounts.putProfile({},e.model.profile,function(e){a.setUserProfile(e).then(function(e){r.success("Account has been updated.","Success!")})}).$promise},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 i(),void r.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+")?")&&o.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),r.success("You have left the organization."),i()})},function(e){r.error("Unable to leave this organization."),i()})},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"})}}]),angular.module("bit.settings").controller("settingsCreateOrganizationController",["$scope","$state","apiService","cryptoService","toastr","$analytics","authService","stripe","constants",function(e,t,n,o,r,a,i,s,l){e.plans=l.plans,e.storageGb=l.storageGb,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.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(l){function c(e){a.eventTrack("Created Organization"),i.addProfileOrganizationOwner(e,d),i.refreshAccessToken().then(function(){u(e.Id)},function(){u(e.Id)})}function u(e){t.go("backend.org.dashboard",{orgId:e}).then(function(){r.success("Your new organization is ready to go!","Organization Created")})}var d=o.makeShareKeyCt();if("free"===l.plan){var p={name:l.name,planType:l.plan,key:d,billingEmail:l.billingEmail};e.submitPromise=n.organizations.post(p).$promise.then(c)}else e.submitPromise=s.card.createToken(l.card).then(function(t){var o={name:l.name,planType:"month"===l.interval?e.plans[l.plan].monthPlanType:e.plans[l.plan].annualPlanType,key:d,paymentToken:t.id,additionalSeats:l.additionalSeats,additionalStorageGb:l.additionalStorageGb,billingEmail:l.billingEmail,businessName:l.ownedBusiness?l.businessName:null};return n.organizations.post(o).$promise},function(e){throw e.message}).then(c)}}]),angular.module("bit.settings").controller("settingsDeleteController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics",function(e,t,n,o,r,a,i,s){s.eventTrack("settingsDeleteController",{category:"Modal"}),e.submit=function(l){e.submitPromise=r.hashPassword(l.masterPassword).then(function(e){return n.accounts.postDelete({masterPasswordHash:e}).$promise}).then(function(){return o.dismiss("cancel"),a.logOut(),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(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsDomainsController",["$scope","$state","apiService","toastr","$analytics","$uibModal",function(e,t,n,o,r,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){r.eventTrack("Saved Equivalent Domains"),o.success("Domains have been updated.","Success!")}).$promise}}]),angular.module("bit.settings").controller("settingsPremiumController",["$scope","$state","apiService","toastr","$analytics","authService","stripe","constants","$timeout","appSettings",function(e,t,n,o,r,a,i,s,l,c){function u(t){return"paypal"===e.paymentMethod?d.requestPaymentMethod().then(function(e){return e.nonce}).catch(function(e){throw e.message}):i.card.createToken(t.card).then(function(e){return e.id}).catch(function(e){throw e.message})}a.getUserProfile().then(function(e){if(e.premium)return t.go("backend.user.settingsBilling")});var d=null;e.storageGbPrice=s.storageGb.yearlyPrice,e.premiumPrice=s.premium.price,e.paymentMethod="card",e.dropinLoaded=!1,e.model={additionalStorageGb:null},e.changePaymentMethod=function(){"paypal"===e.paymentMethod&&braintree.dropin.create({authorization:c.braintreeKey,container:"#bt-dropin-container",paymentOptionPriority:["paypal"],paypal:{flow:"vault",buttonStyle:{label:"pay",size:"medium",shape:"pill",color:"blue"}}},function(t,n){if(t)return void console.error(t);d=n,l(function(){e.dropinLoaded=!0})})},e.totalPrice=function(){return e.premiumPrice+(e.model.additionalStorageGb||0)*e.storageGbPrice},e.submit=function(i){e.submitPromise=u(i).then(function(e){if(!e)throw"No payment token.";var t={paymentToken:e,additionalStorageGb:i.additionalStorageGb};return n.accounts.postPremium(t).$promise},function(e){throw e}).then(function(e){return a.updateProfilePremium(!0)}).then(function(){return r.eventTrack("Signed Up Premium"),a.refreshAccessToken()}).then(function(){return t.go("backend.user.settingsBilling")}).then(function(){o.success("Premium upgrade complete.","Success")})}}]),angular.module("bit.settings").controller("settingsSessionsController",["$scope","$state","apiService","$uibModalInstance","cryptoService","authService","tokenService","toastr","$analytics",function(e,t,n,o,r,a,i,s,l){l.eventTrack("settingsSessionsController",{category:"Modal"}),e.submit=function(c){var u,d;e.submitPromise=r.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 o.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(){o.dismiss("cancel")}}]),angular.module("bit.settings").controller("settingsTwoStepAuthenticatorController",["$scope","apiService","$uibModalInstance","cryptoService","authService","$q","toastr","$analytics","constants","$timeout",function(e,t,n,o,r,a,i,s,l,c){function u(e){return e?e.replace(/(.{4})/g,"$1 ").trim().toUpperCase():null}function d(t){e.enabled=t.Enabled,v=t.Key,e.model={key:u(v),
qr:"https://chart.googleapis.com/chart?chs=120x120&chld=L|0&cht=qr&chl=otpauth://totp/"+f+":"+encodeURIComponent(h.email)+"%3Fsecret="+encodeURIComponent(v)+"%26issuer="+f},e.updateModel={token:null}}function p(){confirm("Are you sure you want to disable the authenticator app provider?")&&(e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:g,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)}function m(n){e.submitPromise=t.twoFactor.putAuthenticator({},{token:n.token.replace(" ",""),key:v,masterPasswordHash:g},function(e){s.eventTrack("Enabled Two-step Authenticator"),d(e),n.token=null}).$promise}s.eventTrack("settingsTwoStepAuthenticatorController",{category:"Modal"});var g,f="bitwarden",h=null,v=null;c(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return g=e,t.twoFactor.getAuthenticator({},{masterPasswordHash:g}).$promise}).then(function(e){return a=e,r.getUserProfile()}).then(function(t){h=t,e.account=h.email,d(a)})},e.submit=function(e){if(!e||!e.token)return void p();m(e)};var y=!1;e.close=function(){y=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){y||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepController",["$scope","apiService","toastr","$analytics","constants","$filter","$uibModal","authService",function(e,t,n,o,r,a,i,s){e.providers=r.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 o=a("filter")(e.providers,{type:t.Data[n].Type});o.length&&(o[0].enabled=!0)}}),e.edit=function(t){if(!e.premium&&!t.free)return void i.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"});if(t.type===r.twoFactorProvider.authenticator)typeName="Authenticator";else if(t.type===r.twoFactorProvider.email)typeName="Email";else if(t.type===r.twoFactorProvider.yubikey)typeName="Yubi";else if(t.type===r.twoFactorProvider.duo)typeName="Duo";else{if(t.type!==r.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)})},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,o,r,a,i,s){function l(){confirm("Are you sure you want to disable the Duo provider?")&&(e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:d,type:i.twoFactorProvider.duo},function(t){a.eventTrack("Disabled Two-step Duo"),r.success("Duo has been disabled."),e.enabled=t.Enabled,e.close()}).$promise)}function c(n){e.submitPromise=t.twoFactor.putDuo({},{integrationKey:n.ikey,secretKey:n.skey,host:n.host,masterPasswordHash:d},function(e){a.eventTrack("Enabled Two-step Duo"),u(e)}).$promise}function u(t){e.enabled=t.Enabled,e.updateModel={ikey:t.IntegrationKey,skey:t.SecretKey,host:t.Host}}a.eventTrack("settingsTwoStepDuoController",{category:"Modal"});var d;e.updateModel={token:null,host:null,ikey:null,skey:null},s(function(){$("#masterPassword").focus()}),e.auth=function(n){e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return d=e,t.twoFactor.getDuo({},{masterPasswordHash:d}).$promise}).then(function(t){u(t),e.authed=!0})},e.submit=function(t){if(e.enabled)return void l();c(t)};var p=!1;e.close=function(){p=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){p||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepEmailController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout",function(e,t,n,o,r,a,i,s,l){function c(){confirm("Are you sure you want to disable the email provider?")&&(e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:d,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)}function u(n){e.submitPromise=t.twoFactor.putEmail({},{email:n.email.toLowerCase().trim(),token:n.token.replace(" ",""),masterPasswordHash:d},function(t){i.eventTrack("Enabled Two-step Email"),e.enabled=t.Enabled,n.email=t.Email,n.token=null}).$promise}i.eventTrack("settingsTwoStepEmailController",{category:"Modal"});var d,p=null;e.updateModel={token:null,email:null},l(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return d=e,t.twoFactor.getEmail({},{masterPasswordHash:d}).$promise}).then(function(e){return a=e,r.getUserProfile()}).then(function(t){p=t,e.enabled=a.Enabled,e.updateModel.email=e.enabled?a.Email:p.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:d,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(e){if(!e||!e.token)return void c();u(e)};var m=!1;e.close=function(){m=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){m||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepRecoverController",["$scope","apiService","$uibModalInstance","cryptoService","$analytics","$timeout",function(e,t,n,o,r,a){function i(e){return e?e.replace(/(.{4})/g,"$1 ").trim().toUpperCase():null}r.eventTrack("settingsTwoStepRecoverController",{category:"Modal"}),e.code=null,e.auth=function(n){e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return t.twoFactor.getRecover({},{masterPasswordHash:e}).$promise}).then(function(t){e.code=i(t.Code),e.authed=!0})},a(function(){$("#masterPassword").focus()}),e.print=function(){if(e.code){r.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,o,r,a,i,s,l,c){function u(){confirm("Are you sure you want to disable the U2F provider?")&&(e.submitPromise=t.twoFactor.disable({},{masterPasswordHash:p,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)}function d(){e.submitPromise=t.twoFactor.putU2f({},{deviceResponse:e.deviceResponse,masterPasswordHash:p},function(t){i.eventTrack("Enabled Two-step U2F"),e.enabled=t.Enabled,e.challenge=null,e.deviceResponse=null,e.deviceError=!1}).$promise}i.eventTrack("settingsTwoStepU2fController",{category:"Modal"});var p,m=!1;e.deviceResponse=null,e.deviceListening=!1,e.deviceError=!1,l(function(){$("#masterPassword").focus()}),e.auth=function(n){e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return p=e,t.twoFactor.getU2f({},{masterPasswordHash:p}).$promise}).then(function(t){return e.enabled=t.Enabled,e.challenge=t.Challenge,e.authed=!0,e.readDevice()})},e.readDevice=function(){m||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){return e.deviceListening=!1,5===t.errorCode?void e.readDevice():t.errorCode?(l(function(){e.deviceError=!0}),void console.log("error: "+t.errorCode)):void l(function(){e.deviceResponse=JSON.stringify(t)})},10))},e.submit=function(){if(e.enabled)return void u();d()},e.close=function(){m=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){m||(t.preventDefault(),e.close())})}]),angular.module("bit.settings").controller("settingsTwoStepYubiController",["$scope","apiService","$uibModalInstance","cryptoService","authService","toastr","$analytics","constants","$timeout",function(e,t,n,o,r,a,i,s,l){function c(t){e.enabled=t.Enabled,e.updateModel={key1:{key:t.Key1,existingKey:u(t.Key1,"*",44)},key2:{key:t.Key2,existingKey:u(t.Key2,"*",44)},key3:{key:t.Key3,existingKey:u(t.Key3,"*",44)},nfc:!0===t.Nfc||!t.Enabled}}function u(e,t,n){if(!e||!t||e.length>=n)return e;for(var o=(n-e.length)/t.length,r=0;r<o;r++)e+=t;return e}i.eventTrack("settingsTwoStepYubiController",{category:"Modal"});var d,p=null;l(function(){$("#masterPassword").focus()}),e.auth=function(n){var a=null;e.authPromise=o.hashPassword(n.masterPassword).then(function(e){return d=e,t.twoFactor.getYubi({},{masterPasswordHash:d}).$promise}).then(function(e){return a=e,r.getUserProfile()}).then(function(t){p=t,c(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:d},function(e){i.eventTrack("Saved Two-step YubiKey"),a.success("YubiKey saved."),c(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:d,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 m=!1;e.close=function(){m=!0,n.close(e.enabled)},e.$on("modal.closing",function(t,n,o){m||(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,o,r,a,i,s,l,c,u){function d(e){var t=a.makeEncKey(null),o=[],i=n.logins.list({},function(e){for(var n=[],a=0;a<e.Data.length;a++)e.Data[a].OrganizationId||n.push(e.Data[a]);var i=r.decryptLogins(n);o=r.encryptLogins(i,t.encKey)}).$promise,s=[],l=n.folders.list({},function(e){var n=r.decryptFolders(e.Data);s=r.encryptFolders(n,t.encKey)}).$promise,c=a.getPrivateKey("raw"),d=null;return c&&(d=a.encrypt(c,t.encKey,"raw")),u.all([i,l]).then(function(){var r={masterPasswordHash:e,ciphers:o,folders:s,privateKey:d,key:t.encKeyEnc};return n.accounts.putKey(r).$promise},function(){throw"Error while encrypting data."}).then(function(){a.setEncKey(t.encKey,null,!0)})}c.eventTrack("settingsUpdateKeyController",{category:"Modal"}),e.save=function(n){if(a.getEncKey())return void s.addError(n,"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 d(e)}).then(function(){return o.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(){o.dismiss("cancel")}}]),angular.module("bit.services").factory("apiService",["$resource","tokenService","appSettings","$httpParamSerializer",function(e,t,n,o){function r(e){return o(e)}var a={},i=n.apiUri,s=n.identityUri;return a.logins=e(i+"/logins/:id",{},{get:{method:"GET",params:{id:"@id"}},getAdmin:{url:i+"/logins/:id/admin",method:"GET",params:{id:"@id"}},list:{method:"GET",params:{}},post:{method:"POST",params:{}},postAdmin:{url:i+"/logins/admin",method:"POST",params:{}},put:{method:"POST",params:{id:"@id"}},putAdmin:{url:i+"/logins/:id/admin",method:"POST",params:{id:"@id"}},del:{url:i+"/logins/:id/delete",method:"POST",params:{id:"@id"}}}),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"}},getDetails:{url:i+"/ciphers/:id/details",method:"GET",params:{id:"@id"}},list:{method:"GET",params:{includeFolders:!1,includeShared:!0}},listDetails:{url:i+"/ciphers/details",method:"GET",params:{}},listOrganizationDetails:{url:i+"/ciphers/organization-details",method:"GET",params:{}},import:{url:i+"/ciphers/import",method:"POST",params:{}},favorite:{url:i+"/ciphers/:id/favorite",method:"POST",params:{id:"@id"}},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"},postAttachment:{url:i+"/ciphers/:id/attachment",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"}}}),a.organizations=e(i+"/organizations/:id",{},{get:{method:"GET",params:{id:"@id"}},getBilling:{url:i+"/organizations/:id/billing",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"}},del:{url:i+"/organizations/:id/delete",method:"POST",params:{id:"@id"}}}),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",method:"GET",params:{}},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:{}},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:{}},postPremium:{url:i+"/accounts/premium",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:{}}}),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.identity=e(s+"/connect",{},{token:{url:s+"/connect/token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=utf-8"},transformRequest:r,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,o,r,a,i){var s={},l=null;s.logIn=function(r,a,l,c,u){r=r.toLowerCase();var d,p=o.defer();return e.makeKeyAndHash(r,a).then(function(e){d=e;var o={username:r,password:e.hash,grant_type:"password",scope:"api offline_access",client_id:"web"};return l&&void 0!==c&&null!==c?(u=u||!1!==u,o.twoFactorToken=l,o.twoFactorProvider=c,o.twoFactorRemember=u?"1":"0"):n.getTwoFactorToken(r)&&(o.twoFactorToken=n.getTwoFactorToken(r),o.twoFactorProvider=i.twoFactorProvider.remember,o.twoFactorRemember="0"),t.identity.token(o).$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,r),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(r),p.resolve(e.data.TwoFactorProviders2)):p.reject(e)}),p.promise},s.logOut=function(){n.clearTokens(),e.clearKeys(),a.vaultFolders=a.vaultLogins=null,l=null},s.getUserProfile=function(){if(!l)return s.setUserProfile();var e=o.defer();return e.resolve(l),e.promise};var c=null;return s.setUserProfile=function(){return c&&0===c.promise.$$state.status?c.promise:(c=o.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={},o=0;o<t.Organizations.length;o++)n[t.Organizations[o].Id]={id:t.Organizations[o].Id,name:t.Organizations[o].Name,key:t.Organizations[o].Key,status:t.Organizations[o].Status,type:t.Organizations[o].Type,enabled:t.Organizations[o].Enabled,maxCollections:t.Organizations[o].MaxCollections,maxStorageGb:t.Organizations[o].MaxStorageGb,seats:t.Organizations[o].Seats,useGroups:t.Organizations[o].UseGroups,useTotp:t.Organizations[o].UseTotp};l.organizations=n,e.setOrgKeys(n),c.resolve(l)}},function(){c.reject()}),c.promise):(c.reject(),c.promise))},s.addProfileOrganizationOwner=function(t,n){return s.getUserProfile().then(function(o){if(o){o.organizations||(o.organizations={});var r={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,useTotp:t.UseTotp};o.organizations[r.id]=r,l=o,e.addOrgKey(r.id,r.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){}):null},s}]),angular.module("bit.services").factory("cipherService",["cryptoService","apiService","$q","$window",function(e,t,n,o){var r={};return r.decryptLogins=function(e){if(!e)throw"encryptedLogins is undefined or null";for(var t=[],n=0;n<e.length;n++)t.push(r.decryptLogin(e[n]));return t},r.decryptLogin=function(t,n){if(!t)throw"encryptedLogin is undefined or null";var o=null;t.OrganizationId&&(o=e.getOrgKey(t.OrganizationId));var a={id:t.Id,organizationId:t.OrganizationId,collectionIds:t.CollectionIds||[],type:1,folderId:t.FolderId,favorite:t.Favorite,edit:t.Edit,organizationUseTotp:t.OrganizationUseTotp,attachments:null},i=t.Data||t;if(i&&(a.name=e.decrypt(i.Name,o),a.uri=i.Uri&&""!==i.Uri?e.decrypt(i.Uri,o):null,a.username=i.Username&&""!==i.Username?e.decrypt(i.Username,o):null,a.password=i.Password&&""!==i.Password?e.decrypt(i.Password,o):null,a.notes=i.Notes&&""!==i.Notes?e.decrypt(i.Notes,o):null,a.totp=i.Totp&&""!==i.Totp?e.decrypt(i.Totp,o):null),!t.Attachments)return a;a.attachments=[];for(var s=0;s<t.Attachments.length;s++)a.attachments.push(r.decryptAttachment(o,t.Attachments[s]));return a},r.decryptLoginPreview=function(t){if(!t)throw"encryptedCipher is undefined or null";var n=null;t.OrganizationId&&(n=e.getOrgKey(t.OrganizationId));var o={id:t.Id,organizationId:t.OrganizationId,collectionIds:t.CollectionIds||[],folderId:t.FolderId,favorite:t.Favorite,edit:t.Edit,organizationUseTotp:t.OrganizationUseTotp,hasAttachments:!!t.Attachments&&t.Attachments.length>0},a=t.Data||t;return a&&(o.name=r.decryptProperty(a.Name,n,!1),o.username=r.decryptProperty(a.Username,n,!0),o.password=r.decryptProperty(a.Password,n,!0)),o},r.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}},r.downloadAndDecryptAttachment=function(t,r,a){var i=n.defer(),s=new XMLHttpRequest;return s.open("GET",r.url,!0),s.responseType="arraybuffer",s.onload=function(n){if(!s.response)return void i.reject("No response");e.decryptFromBytes(s.response,t).then(function(e){if(a){var t=new Blob([e]);if(o.navigator.msSaveOrOpenBlob)o.navigator.msSaveBlob(t,r.fileName);else{var n=o.document.createElement("a");n.href=o.URL.createObjectURL(t),n.download=r.fileName,o.document.body.appendChild(n),n.click(),o.document.body.removeChild(n)}}i.resolve(new Uint8Array(e))})},s.send(null),i.promise},r.decryptFolders=function(e){if(!e)throw"encryptedFolders is undefined or null";for(var t=[],n=0;n<e.length;n++)t.push(r.decryptFolder(e[n]));return t},r.decryptFolder=function(t){if(!t)throw"encryptedFolder is undefined or null";return{id:t.Id,name:e.decrypt(t.Name)}},r.decryptFolderPreview=function(e){if(!e)throw"encryptedFolder is undefined or null";return{id:e.Id,name:r.decryptProperty(e.Name,null,!1)}},r.decryptCollections=function(e,t,n){if(!e)throw"encryptedCollections is undefined or null";for(var o=[],a=0;a<e.length;a++)o.push(r.decryptCollection(e[a],t,n));return o},r.decryptCollection=function(t,n,o){if(!t)throw"encryptedCollection is undefined or null";o=!0===o,n=n||t.OrganizationId;var a=e.getOrgKey(n);return{id:t.Id,name:o?r.decryptProperty(t.Name,a,!1):e.decrypt(t.Name,a)}},r.decryptProperty=function(t,n,o){if(o&&(!t||""===t))return null;try{t=e.decrypt(t,n)}catch(e){t=null}return t||"[error: cannot decrypt]"},r.encryptLogins=function(e,t){if(!e)throw"unencryptedLogins is undefined or null";for(var n=[],o=0;o<e.length;o++)n.push(r.encryptLogin(e[o],t));return n},r.encryptLogin=function(t,n,o){if(!t)throw"unencryptedLogin is undefined or null";t.organizationId&&(n=n||e.getOrgKey(t.organizationId));var r={id:t.id,type:1,organizationId:t.organizationId||null,folderId:""===t.folderId?null:t.folderId,favorite:null!==t.favorite&&t.favorite,uri:t.uri&&""!==t.uri?e.encrypt(t.uri,n):null,name:e.encrypt(t.name,n),username:t.username&&""!==t.username?e.encrypt(t.username,n):null,password:t.password&&""!==t.password?e.encrypt(t.password,n):null,notes:t.notes&&""!==t.notes?e.encrypt(t.notes,n):null,totp:t.totp&&""!==t.totp?e.encrypt(t.totp,n):null};if(t.attachments&&o){r.attachments={};for(var a=0;a<t.attachments.length;a++)r.attachments[t.attachments[a].id]=e.encrypt(t.attachments[a].fileName,n)}return r},r.encryptAttachmentFile=function(t,o){var r=n.defer();if(o.size>104857600)return void r.reject("Maximum file size is 100 MB.");var a=new FileReader;return a.readAsArrayBuffer(o),a.onload=function(n){e.encryptToBytes(n.target.result,t).then(function(n){r.resolve({fileName:e.encrypt(o.name,t),data:new Uint8Array(n),size:o.size})})},a.onerror=function(e){r.reject("Error reading file.")},r.promise},r.encryptFolders=function(e,t){if(!e)throw"unencryptedFolders is undefined or null";for(var n=[],o=0;o<e.length;o++)n.push(r.encryptFolder(e[o],t));return n},r.encryptFolder=function(t,n){if(!t)throw"unencryptedFolder is undefined or null";return{id:t.id,name:e.encrypt(t.name,n)}},r.encryptCollections=function(e,t){if(!e)throw"unencryptedCollections is undefined or null";for(var n=[],o=0;o<e.length;o++)n.push(r.encryptCollection(e[o],t));return n},r.encryptCollection=function(t,n){if(!t)throw"unencryptedCollection is undefined or null";return{id:t.id,name:e.encrypt(t.name,e.getOrgKey(n))}},r}]),angular.module("bit.services").factory("cryptoService",["$sessionStorage","constants","$q","$window",function(e,t,n,o){function r(e,t,n,o){return e="string"==typeof e?f(e):e,t="string"==typeof t?f(t):t,$.importKey("raw",e.buffer,{name:"PBKDF2"},!1,["deriveKey","deriveBits"]).then(function(e){return $.deriveKey({name:"PBKDF2",salt:t.buffer,iterations:n,hash:{name:"SHA-256"}},e,{name:"AES-CBC",length:o},!0,["encrypt","decrypt"])}).then(function(e){return $.exportKey("raw",e)})}function a(e,t,n){if(!(t=t||k.getEncKey()||k.getKey()))throw"Encryption key unavailable.";n=n||"utf8";var o=forge.util.createBuffer(e,n),r=forge.random.getBytesSync(16),a=forge.cipher.createCipher("AES-CBC",t.encKey);a.start({iv:r}),a.update(o),a.finish();var i=a.output.getBytes(),s=null;return t.macKey&&(s=l(r+i,t.macKey,!1)),{iv:r,ct:i,mac:s,key:t,plainValueEncoding:n}}function i(e,t){if(!(t=t||k.getEncKey()||k.getKey()))throw"Encryption key unavailable.";var n={iv:new Uint8Array(16),ct:null,mac:null,key:t},o=t.getBuffers();return P.getRandomValues(n.iv),$.importKey("raw",o.encKey,{name:"AES-CBC"},!1,["encrypt"]).then(function(t){return $.encrypt({name:"AES-CBC",iv:n.iv},t,e)}).then(function(e){if(n.ct=new Uint8Array(e),!o.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),c(t.buffer,o.macKey)}).then(function(e){return e&&(n.mac=new Uint8Array(e)),n})}function s(e,t,n,o,r){if(!(r=r||k.getEncKey()||k.getKey()))throw"Encryption key unavailable.";if(e!==r.encType)throw"encType unavailable.";var a=r.getBuffers(),i=null;return $.importKey("raw",a.encKey,{name:"AES-CBC"},!1,["decrypt"]).then(function(e){if(i=e,!r.macKey||!o)return null;var s=new Uint8Array(n.byteLength+t.byteLength);return s.set(new Uint8Array(n),0),s.set(new Uint8Array(t),n.byteLength),c(s.buffer,a.macKey)}).then(function(e){return null===e?null:d(a.macKey,o,e)}).then(function(e){return!1===e?(console.error("MAC failed."),null):$.decrypt({name:"AES-CBC",iv:n},i,t)})}function l(e,t,n){var o=forge.hmac.create();o.start("sha256",t),o.update(e);var r=o.digest();return n?forge.util.encode64(r.getBytes()):r.getBytes()}function c(e,t){return $.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]).then(function(t){return $.sign({
name:"HMAC",hash:{name:"SHA-256"}},t,e)})}function u(e,t,n){var o=forge.hmac.create();return o.start("sha256",e),o.update(t),t=o.digest().getBytes(),o.start(null,null),o.update(n),n=o.digest().getBytes(),t===n}function d(e,t,n){var o,r;return window.crypto.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]).then(function(e){return r=e,window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-256"}},r,t)}).then(function(e){return o=e,window.crypto.subtle.sign({name:"HMAC",hash:{name:"SHA-256"}},r,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})}function p(e,n,o){if(n&&(e=forge.util.decode64(e)),!e)throw"Must provide keyBytes";var r=forge.util.createBuffer(e);if(!r||0===r.length())throw"Couldn't make buffer";var a=r.length();if(null===o||void 0===o)if(32===a)o=t.encType.AesCbc256_B64;else{if(64!==a)throw"Unable to determine encType.";o=t.encType.AesCbc256_HmacSha256_B64}if(this.key=e,this.keyB64=forge.util.encode64(e),this.encType=o,o===t.encType.AesCbc256_B64&&32===a)this.encKey=e,this.macKey=null;else if(o===t.encType.AesCbc128_HmacSha256_B64&&32===a)this.encKey=r.getBytes(16),this.macKey=r.getBytes(16);else{if(o!==t.encType.AesCbc256_HmacSha256_B64||64!==a)throw"Unsupported encType/key length.";this.encKey=r.getBytes(32),this.macKey=r.getBytes(32)}}function m(e){for(var t=o.atob(e),n=new Uint8Array(t.length),r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function g(e){for(var t="",n=new Uint8Array(e),r=0;r<n.byteLength;r++)t+=String.fromCharCode(n[r]);return o.btoa(t)}function f(e){for(var t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}function h(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 o=new ArrayBuffer(n-t),r=new Uint8Array(o),a=new Uint8Array(e,t,n-t);return r.set(a),new Uint8Array(o)}var v,y,b,w,S,C,k={},P=void 0!==o.crypto?o.crypto:null,$=P&&void 0!==o.crypto.subtle?o.crypto.subtle:null;return k.setKey=function(t){v=t,e.key=v.keyB64},k.setEncKey=function(t,n,o){if(o)return y=t,void(e.encKey=y.keyB64);try{var r=k.decrypt(t,n,"raw");e.encKey=forge.util.encode64(r),y=new p(r)}catch(e){console.log("Cannot set enc key. Decryption failed.")}},k.setPrivateKey=function(t,n){try{var o=k.decrypt(t,n,"raw");e.privateKey=forge.util.encode64(o),S=forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(o))}catch(e){console.log("Cannot set private key. Decryption failed.")}},k.setOrgKeys=function(t,n){if(t&&0!==Object.keys(t).length){k.clearOrgKeys();var o={},r={},a=!1;for(var i in t)if(t.hasOwnProperty(i))try{var s=k.rsaDecrypt(t[i].key,n),l=new p(s);r[i]=l,o[i]=l.keyB64,a=!0}catch(e){console.log("Cannot set org key for "+i+". Decryption failed.")}a?e.orgKeys=o:r=null}},k.addOrgKey=function(t,n,o){(w=k.getOrgKeys())||(w={});var r=e.orgKeys;r||(r={});try{var a=k.rsaDecrypt(n,o),i=new p(a);w[t]=i,r[t]=i.keyB64}catch(e){w=null,console.log("Cannot set org key. Decryption failed.")}e.orgKeys=r},k.getKey=function(){if(!v&&e.key&&(v=new p(e.key,!0)),!v)throw"key unavailable";return v},k.getEncKey=function(){return!y&&e.encKey&&(y=new p(e.encKey,!0)),y},k.getPrivateKey=function(t){if(t=t||"native",S){if("raw"===t){var n=forge.pki.privateKeyToAsn1(S),o=forge.pki.wrapRsaPrivateKey(n);return forge.asn1.toDer(o).getBytes()}return S}if(e.privateKey){var r=forge.util.decode64(e.privateKey);if(S=forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(r)),"raw"===t)return r}return S},k.getPublicKey=function(){if(C)return C;var e=k.getPrivateKey();return e?C=forge.pki.setRsaPublicKey(e.n,e.e):null},k.getOrgKeys=function(){if(w)return w;if(e.orgKeys){var t={},n=!1;for(var o in e.orgKeys)e.orgKeys.hasOwnProperty(o)&&(t[o]=new p(e.orgKeys[o],!0),n=!0);n&&(w=t)}return w},k.getOrgKey=function(e){var t=k.getOrgKeys();return t&&e in t?t[e]:null},k.clearKey=function(){v=null,b=null,delete e.key},k.clearEncKey=function(){y=null,delete e.encKey},k.clearKeyPair=function(){S=null,C=null,delete e.privateKey},k.clearOrgKeys=function(){w=null,delete e.orgKeys},k.clearOrgKey=function(t){w.hasOwnProperty(t)&&delete w[t],e.orgKeys.hasOwnProperty(t)&&delete e.orgKeys[t]},k.clearKeys=function(){k.clearKey(),k.clearEncKey(),k.clearKeyPair(),k.clearOrgKeys()},k.makeKey=function(e,t){if(o.cryptoShimmed||-1!==o.navigator.userAgent.indexOf("Edge")){var a=n.defer(),i=forge.pbkdf2(forge.util.encodeUtf8(e),forge.util.encodeUtf8(t),5e3,32,"sha256");return a.resolve(new p(i)),a.promise}return r(e,t,5e3,256).then(function(e){return new p(g(e),!0)})},k.makeEncKey=function(e){var t=forge.random.getBytesSync(64),n=k.encrypt(t,e,"raw");return{encKey:new p(t),encKeyEnc:n}},k.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,o){if(n)return void t.reject(n);var r=forge.pki.privateKeyToAsn1(o.privateKey),a=forge.pki.wrapRsaPrivateKey(r),i=forge.asn1.toDer(a).getBytes(),s=k.encrypt(i,e,"raw"),l=forge.pki.publicKeyToAsn1(o.publicKey),c=forge.asn1.toDer(l).getBytes();t.resolve({publicKey:forge.util.encode64(c),privateKeyEnc:s})}),t.promise},k.makeShareKeyCt=function(){return k.rsaEncryptMe(forge.random.getBytesSync(64))},k.hashPassword=function(e,t){if(t||(t=k.getKey()),!e||!t)throw"Invalid parameters.";if(o.cryptoShimmed||-1!==o.navigator.userAgent.indexOf("Edge")){var a=n.defer(),i=forge.pbkdf2(t.key,forge.util.encodeUtf8(e),1,32,"sha256");return a.resolve(forge.util.encode64(i)),a.promise}var s=t.getBuffers();return r(new Uint8Array(s.key),e,1,256).then(function(e){return g(e)})},k.makeKeyAndHash=function(e,t){e=e.toLowerCase();var n;return k.makeKey(t,e).then(function(e){return n=e,k.hashPassword(t,e)}).then(function(e){return{key:n,hash:e}})},k.encrypt=function(e,t,n){var o=a(e,t,n),r=forge.util.encode64(o.iv),i=forge.util.encode64(o.ct),s=r+"|"+i;if(o.mac){s=s+"|"+forge.util.encode64(o.mac)}return o.key.encType+"."+s},k.encryptToBytes=function(e,t){return i(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})},k.rsaEncrypt=function(e,n,o){if(!(n=n||k.getPublicKey()))throw"Public key unavailable.";if("string"==typeof n){var r=forge.util.decode64(n);n=forge.pki.publicKeyFromAsn1(forge.asn1.fromDer(r))}var a=n.encrypt(e,"RSA-OAEP",{md:forge.md.sha1.create()}),i=forge.util.encode64(a);if(o&&o.macKey){var s=l(a,o.macKey,!0);return t.encType.Rsa2048_OaepSha1_HmacSha256_B64+"."+i+"|"+s}return t.encType.Rsa2048_OaepSha1_B64+"."+i},k.rsaEncryptMe=function(e){return k.rsaEncrypt(e,k.getPublicKey(),k.getEncKey())},k.decrypt=function(e,n,o){try{n=n||k.getEncKey()||k.getKey();var r,a,i=e.split(".");if(2===i.length)try{r=parseInt(i[0]),a=i[1].split("|")}catch(e){return console.error("Cannot parse headerPieces."),null}else a=e.split("|"),r=3===a.length?t.encType.AesCbc128_HmacSha256_B64:t.encType.AesCbc256_B64;if(r===t.encType.AesCbc128_HmacSha256_B64&&n.encType===t.encType.AesCbc256_B64&&(b=b||new p(n.key,!1,t.encType.AesCbc128_HmacSha256_B64),n=b),r!==n.encType)throw"encType unavailable.";switch(r){case t.encType.AesCbc128_HmacSha256_B64:case t.encType.AesCbc256_HmacSha256_B64:if(3!==a.length)return console.error("Enc type ("+r+") not valid."),null;break;case t.encType.AesCbc256_B64:if(2!==a.length)return console.error("Enc type ("+r+") not valid."),null;break;default:return console.error("Enc type ("+r+") not supported."),null}var s=forge.util.decode64(a[0]),c=forge.util.decode64(a[1]);if(n.macKey&&a.length>2){var d=forge.util.decode64(a[2]),m=l(s+c,n.macKey,!1);if(!u(n.macKey,d,m))return console.error("MAC failed."),null}var g=forge.util.createBuffer(c),f=forge.cipher.createDecipher("AES-CBC",n.encKey);return f.start({iv:s}),f.update(g),f.finish(),o=o||"utf8","utf8"===o?f.output.toString("utf8"):f.output.getBytes()}catch(e){throw console.error("Caught unhandled error in decrypt: "+e),e}},k.decryptFromBytes=function(e,n){try{if(!e)throw"no encBuf.";var o=new Uint8Array(e),r=o[0],a=null,i=null,l=null;switch(r){case t.encType.AesCbc128_HmacSha256_B64:case t.encType.AesCbc256_HmacSha256_B64:if(o.length<=49)return console.error("Enc type ("+r+") not valid."),null;i=h(o,1,17),l=h(o,17,49),a=h(o,49);break;case t.encType.AesCbc256_B64:if(o.length<=17)return console.error("Enc type ("+r+") not valid."),null;i=h(o,1,17),a=h(o,17);break;default:return console.error("Enc type ("+r+") not supported."),null}return s(r,a.buffer,i.buffer,l?l.buffer:null,n)}catch(e){throw console.error("Caught unhandled error in decryptFromBytes: "+e),e}},k.rsaDecrypt=function(e,n,o){if(n=n||k.getPrivateKey(),o=o||k.getEncKey(),!n)throw"Private key unavailable.";var r,a,i=e.split(".");if(1===i.length)r=t.encType.Rsa2048_OaepSha256_B64,a=[i[0]];else if(2===i.length)try{r=parseInt(i[0]),a=i[1].split("|")}catch(e){return null}switch(r){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=forge.util.decode64(a[0]);if(o&&o.macKey&&a.length>1){var c=forge.util.decode64(a[1]),d=l(s,o.macKey,!1);if(!u(o.macKey,c,d))return console.error("MAC failed."),null}var p;if(r===t.encType.Rsa2048_OaepSha256_B64||r===t.encType.Rsa2048_OaepSha256_HmacSha256_B64)p=forge.md.sha256.create();else{if(r!==t.encType.Rsa2048_OaepSha1_B64&&r!==t.encType.Rsa2048_OaepSha1_HmacSha256_B64)throw"encType unavailable.";p=forge.md.sha1.create()}return n.decrypt(s,"RSA-OAEP",{md:p})},p.prototype.getBuffers=function(){if(this.keyBuf)return this.keyBuf;var e=m(this.keyB64),t={key:e.buffer};return this.macKey?(t.encKey=h(e,0,e.length/2).buffer,t.macKey=h(e,e.length/2).buffer):(t.encKey=e.buffer,t.macKey=null),this.keyBuf=t,this.keyBuf},k}]),angular.module("bit.services").factory("importService",function(){function e(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 t(e){return e=e.toLowerCase().trim(),!e.startsWith("http")&&e.indexOf(".")>=0&&(e="http://"+e),n(e)}function n(e){return e.length>1e3?e.substring(0,1e3):e}function o(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 r(e,t,n){if("string"==typeof e)t(e);else{var o=new FileReader;o.readAsText(e,"utf-8"),o.onload=function(e){t(e.target.result)},o.onerror=function(e){n()}}}function a(e,t,n){r(e,function(e){t($.parseXML(e))},n)}function i(e,t,r){Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e);var r=[],a=[],i=[];angular.forEach(e.data,function(e,t){var o=r.length,s=a.length,l=e.folder&&""!==e.folder,c=l;if(l)for(var u=0;u<r.length;u++)if(r[u].name===e.folder){c=!1,o=u;break}if(a.push({favorite:!(!e.favorite||""===e.favorite||"0"===e.favorite),uri:e.uri&&""!==e.uri?n(e.uri):null,username:e.username&&""!==e.username?e.username:null,password:e.password&&""!==e.password?e.password:null,notes:e.notes&&""!==e.notes?e.notes:null,name:e.name&&""!==e.name?e.name:"--",totp:e.totp&&""!==e.totp?e.totp:null}),c&&r.push({name:e.folder}),l){var d={key:s,value:o};i.push(d)}}),t(r,a,i)}})}function s(e,t,r){function a(e){var o=[],r=[],a=[];angular.forEach(e,function(e,t){var i=o.length,s=r.length,l=e.grouping&&""!==e.grouping&&"(none)"!==e.grouping,c=l;if(l)for(var u=0;u<o.length;u++)if(o[u].name===e.grouping){c=!1,i=u;break}if(r.push({favorite:"1"===e.fav,uri:e.url&&""!==e.url?n(e.url):null,username:e.username&&""!==e.username?e.username:null,password:e.password&&""!==e.password?e.password:null,notes:e.extra&&""!==e.extra?e.extra:null,name:e.name&&""!==e.name?e.name:"--"}),c&&o.push({name:e.grouping}),l){var d={key:s,value:i};a.push(d)}}),t(o,r,a)}if("string"!=typeof e&&e.type&&"text/html"===e.type){var i=new FileReader;i.readAsText(e,"utf-8"),i.onload=function(e){var t,n,o=$(e.target.result),i=o.find("pre");if(1===i.length)t=i.text().trim(),n=Papa.parse(t,{header:!0,encoding:"UTF-8"}),a(n.data);else{for(var s=!1,l=0;l<o.length;l++)if("pre"===o[l].tagName.toLowerCase()){s=!0,t=o[l].outerText.trim(),n=Papa.parse(t,{header:!0,encoding:"UTF-8"}),a(n.data);break}s||r()}},i.onerror=function(e){r()}}else Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e),a(e.data)},beforeFirstChunk:function(e){return e.replace(/^\s+/,"")}})}function l(e,t,o){function r(e){var r=$(e),a=r.find("database");if(a.length){var p=a.find("> label");if(p.length)for(u=0;u<p.length;u++){var m=$(p[u]);c[m.attr("id")]=i.length,i.push({name:m.attr("name")})}var g=a.find("> card");if(g.length)for(u=0;u<g.length;u++){var f=$(g[u]);if("true"!==f.attr("template")){var h={favorite:!1,uri:null,username:null,password:null,notes:"",name:f.attr("title")},v=f.find("> field");for(d=0;d<v.length;d++){var y=$(v[d]),b=y.text(),w=y.attr("type"),S=y.attr("name");b&&""!==b&&("login"===w?h.username=b:"password"===w?h.password=b:"notes"===w?h.notes+=b+"\n":"weblogin"===w||"website"===w?h.uri=n(b):h.notes+=S+": "+b+"\n")}var C=f.find("> notes");for(d=0;d<C.length;d++)h.notes+=$(C[d]).text()+"\n";if(""===h.notes&&(h.notes=null),s.push(h),p=f.find("> label_id"),p.length){var k=$(p[0]).text(),P=c[k];null!==k&&""!==k&&null!==P&&l.push({key:s.length-1,value:P})}}}t(i,s,l)}else o()}var i=[],s=[],l=[],c=[],u=0,d=0;a(e,r,o)}function c(e,t,r){Papa.parse(e,{encoding:"UTF-8",complete:function(e){o(e);var r=[],a=[],i=[],s=[],l=0,c=0;for(l=0;l<e.data.length;l++){var u=e.data[l];if(0!==l){var d=r.length,p=a.length,m=u[1]&&""!==u[1],g=m;if(m)for(c=0;c<r.length;c++)if(r[c].name===u[1]){g=!1,d=c;break}var f={favorite:!1,uri:null,username:u[2]&&""!==u[2]?u[2]:null,password:u[3]&&""!==u[3]?u[3]:null,notes:null,name:u[0]&&""!==u[0]?u[0]:"--"};if(s.length)for(c=4;c<u.length;c++){var h=u[c];if(h&&""!==h){var v=s[c-4];"url"===v.toLowerCase()||"uri"===v.toLowerCase()?f.uri=n(h):(null===f.notes&&(f.notes=""),f.notes+=v+": "+h+"\n")}}a.push(f),g&&r.push({name:u[1]}),m&&i.push({key:p,value:d})}else for(c=4;c<u.length;c++)s.push(u[c])}t(r,a,i)}})}function u(e,t,o){function r(e){var n=$(e),r=n.find("Root");if(r.length){var a=r.find("> Group");a.length&&(i($(a[0]),!0,""),t(s,l,c))}else o()}function i(e,t,o){var r=s.length,a=o;t||(""!==a&&(a+=" > "),a+=e.find("> Name").text(),s.push({name:a}));var u=e.find("> Entry");if(u.length)for(var d=0;d<u.length;d++){for(var p=$(u[d]),m=l.length,g={favorite:!1,uri:null,username:null,password:null,notes:null,name:null},f=p.find("> String"),h=0;h<f.length;h++){var v=$(f[h]),y=v.find("> Key").text(),b=v.find("> Value").text();if(""!==b)switch(y){case"URL":g.uri=n(b);break;case"UserName":g.username=b;break;case"Password":g.password=b;break;case"Title":g.name=b;break;case"Notes":g.notes=null===g.notes?b+"\n":g.notes+b+"\n";break;default:g.notes=null===g.notes?y+": "+b+"\n":g.notes+y+": "+b+"\n"}}null===g.name&&(g.name="--"),l.push(g),t||c.push({key:m,value:r})}var w=e.find("> Group");if(w.length)for(var S=0;S<w.length;S++)i($(w[S]),!1,a)}var s=[],l=[],c=[];a(e,r,o)}function d(e,n,r){Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e);var r=[],a=[],i=[];angular.forEach(e.data,function(e,n){e.Group=e.Group.startsWith("Root/")?e.Group.replace("Root/",""):e.Group;var o=e.Group&&""!==e.Group?e.Group.split("/").join(" > "):null,s=r.length,l=a.length,c=null!==o,u=c,d=0;if(c)for(d=0;d<r.length;d++)if(r[d].name===o){u=!1,s=d;break}var p={favorite:!1,uri:e.URL&&""!==e.URL?t(e.URL):null,username:e.Username&&""!==e.Username?e.Username:null,password:e.Password&&""!==e.Password?e.Password:null,notes:e.Notes&&""!==e.Notes?e.Notes:null,name:e.Title&&""!==e.Title?e.Title:"--"};if(e.Title&&a.push(p),u&&r.push({name:o}),c){var m={key:l,value:s};i.push(m)}}),n(r,a,i)}})}function p(e,n,o){function a(e,t,n,o,r){for(var a=0;a<e.length;a++){var i=e[a];i[o]&&""!==i[o]&&(!t.username&&i[n]&&"username"===i[n]?t.username=i[o]:!t.password&&i[n]&&"password"===i[n]?t.password=i[o]:i[r]&&i[o]&&(null===t.notes?t.notes="":t.notes+="\n",t.notes+=i[r]+": "+i[o].toString().split("\\r\\n").join("\n").split("\\n").join("\n")))}}function i(e){var o=e.split(/(?:\r\n|\r|\n)/);for(u=0;u<o.length;u++){var r=o[u];if(r.length&&"{"===r[0]){var i=JSON.parse(r),d={favorite:!(!i.openContents||!i.openContents.faveIndex),uri:i.location&&""!==i.location?t(i.location):null,username:null,password:null,notes:null,name:i.title&&""!==i.title?i.title:"--"};if(i.secureContents&&(i.secureContents.notesPlain&&""!==i.secureContents.notesPlain&&(d.notes=i.secureContents.notesPlain.split("\\r\\n").join("\n").split("\\n").join("\n")),i.secureContents.fields&&a(i.secureContents.fields,d,"designation","value","name"),i.secureContents.sections))for(var p=0;p<i.secureContents.sections.length;p++)i.secureContents.sections[p].fields&&a(i.secureContents.sections[p].fields,d,"n","v","t");l.push(d)}}n(s,l,c)}var s=[],l=[],c=[],u=0;r(e,i,o)}function m(e,n,r){var a=[],i=[],s=[];Papa.parse(e,{encoding:"UTF-8",header:!0,complete:function(e){o(e);for(var r=0;r<e.data.length;r++){var l=e.data[r];if(l.title){var c={favorite:!1,uri:null,username:null,password:null,notes:l.notesPlain&&""!==l.notesPlain?l.notesPlain:"",name:l.title&&""!==l.title?l.title:"--"};for(var u in l)if(l.hasOwnProperty(u)){if(null===l[u]||""===l[u])continue;if(c.password||"password"!==u)if(c.username||"username"!==u)if(c.uri||"urls"!==u)"ainfo"===u||"autosubmit"===u||"notesPlain"===u||"ps"===u||"scope"===u||"tags"===u||"title"===u||"uuid"===u||u.startsWith("section:")||(""!==c.notes&&(c.notes+="\n"),c.notes+=u+": "+l[u]);else{var d=l[u].split(/(?:\r\n|\r|\n)/);c.uri=t(d[0]);for(var p=1;p<d.length;p++)""!==c.notes&&(c.notes+="\n"),c.notes+="url "+(p+1)+": "+d[p]}else c.username=l[u];else c.password=l[u]}""===c.notes&&(c.notes=null),i.push(c)}}n(a,i,s)}})}function g(e,t,r){Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e);var r=[],a=[],i=[];angular.forEach(e.data,function(e,t){a.push({favorite:!1,uri:e.url&&""!==e.url?n(e.url):null,username:e.username&&""!==e.username?e.username:null,password:e.password&&""!==e.password?e.password:null,notes:null,name:e.name&&""!==e.name?e.name:"--"})}),t(r,a,i)}})}function f(e,t,o){function r(e){var t="--";try{if(e&&""!==e){var n=document.createElement("a");n.href=e,n.hostname&&(t=n.hostname)}}catch(e){}return t}function i(e){for(var o=$(e),a=o.find("entry"),i=0;i<a.length;i++){var u=$(a[i]);if(u){var d=u.attr("host"),p=u.attr("user"),m=u.attr("password");l.push({favorite:!1,uri:d&&""!==d?n(d):null,username:p&&""!==p?p:null,password:m&&""!==m?m:null,notes:null,name:r(d)})}}t(s,l,c)}var s=[],l=[],c=[];if(!e.type||"text/xml"!==e.type)return void o("Only .xml exports are supported.");a(e,i,o)}function h(e,t,r){Papa.parse(e,{encoding:"UTF-8",complete:function(e){o(e);var r=[],a=[],i=[];angular.forEach(e.data,function(e,t){5===e.length&&a.push({favorite:!1,uri:e[3]&&""!==e[3]?n(e[3]):null,username:e[1]&&""!==e[1]?e[1]:null,password:e[2]&&""!==e[2]?e[2]:null,notes:e[4]&&""!==e[4]?e[4]:null,name:e[0]&&""!==e[0]?e[0]:"--"})}),t(r,a,i)}})}function v(e,t,r){Papa.parse(e,{encoding:"UTF-8",complete:function(e){o(e);var r=[],a=[],i=[];angular.forEach(e.data,function(e,t){if(e.length>=6){var o=r.length,s=a.length,l=e[0]&&""!==e[0],c=l,u=0;if(l)for(u=0;u<r.length;u++)if(r[u].name===e[0]){c=!1,o=u;break}var d={favorite:!1,uri:e[4]&&""!==e[4]?n(e[4]):null,username:e[2]&&""!==e[2]?e[2]:null,password:e[3]&&""!==e[3]?e[3]:null,notes:e[5]&&""!==e[5]?e[5]:null,name:e[1]&&""!==e[1]?e[1]:"--"};if(e.length>6)for(null===d.notes?d.notes="":d.notes+="\n",u=6;u<e.length;u+=2){var p=e[u],m=e[u+1];d.notes+=p+": "+m+"\n"}if(a.push(d),c&&r.push({name:e[0]}),l){var g={key:s,value:o};i.push(g)}}}),t(r,a,i)}})}function y(e,t,o){function r(e){var r=$(e),a=r.find("PasswordManager");if(a.length){var u=a.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,S=p.find("> Notes"),C=S.length?$(S):null,k=p.find("> Category"),P=k.length?$(k):null,I=P?P.text():null,T=i.length,A=s.length,z=I&&""!==I&&"Unfiled"!==I,O=z;if(z)for(c=0;c<i.length;c++)if(i[c].name===I){O=!1,T=c;break}var E={favorite:!1,uri:w&&""!==w.text()?n(w.text()):null,username:h&&""!==h.text()?h.text():null,password:y&&""!==y.text()?y.text():null,notes:C&&""!==C.text()?C.text():null,name:g&&""!==g.text()?g.text():"--"},U="";for(c=1;c<=10;c++)U+="> Attribute-"+c,c<10&&(U+=", ");var F=p.find(U);if(F.length)for(c=0;c<F.length;c++){var x=$(F[c]),D=x.prop("tagName"),L=x.text();L&&""!==L&&"null"!==L&&(null===E.notes?E.notes="":E.notes+="\n",E.notes+=D+": "+L)}if(s.push(E),O&&i.push({name:I}),z){var M={key:A,value:T};l.push(M)}}t(i,s,l)}else o()}var i=[],s=[],l=[],c=0;a(e,r,o)}function b(e,t,r){Papa.parse(e,{encoding:"UTF-8",complete:function(e){o(e);for(var r=[],a=[],i=[],s=0;s<e.data.length;s++){var l=e.data[s];if(!(l.length<2)&&(0!==s||"Title"!==l[0])){var c=l[l.length-1],u={name:l[0],favorite:!1,uri:null,password:null,username:null,notes:c&&""!==c?c:null};if(l.length>2&&l.length%2==0)for(var d=0;d<l.length-2;d+=2){var p=l[d+2];if(p&&""!==p){var m=l[d+1],g=m.toLowerCase();"url"!==g||u.uri?"username"!==g&&"email"!==g||u.username?"password"!==g||u.password?u.notes=null===u.notes?m+": "+p:u.notes+"\n"+m+": "+p:u.password=p:u.username=p:u.uri=n(p)}}a.push(u)}}t(r,a,i)}})}function w(e,t,o){function r(e){var r=$(e),a=r.find("passwordsafe");if(a.length){var u=a.attr("delimiter"),d=a.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,S=m.find("> password"),C=S.length?$(S):null,k=m.find("> url"),P=k.length?$(k):null,I=m.find("> notes"),T=I.length?$(I):null,A=T?T.text().split(u).join("\n"):null,z=m.find("> group"),O=z.length?$(z):null,E=O?O.text().split(".").join(" > "):null,U=i.length,F=s.length,x=E&&""!==E,D=x;if(x)for(c=0;c<i.length;c++)if(i[c].name===E){D=!1,U=c;break}var L={favorite:!1,uri:P&&""!==P.text()?n(P.text()):null,username:v&&""!==v.text()?v.text():null,password:C&&""!==C.text()?C.text():null,notes:T&&""!==A?A:null,name:f&&""!==f.text()?f.text():"--"};if(!L.username&&w&&""!==w?L.username=w:w&&""!==w&&(L.notes=null===L.notes?"Email: "+w:L.notes+"\nEmail: "+w),s.push(L),D&&i.push({name:E}),x){var M={key:F,value:U};l.push(M)}}t(i,s,l)}else o()}var i=[],s=[],l=[],c=0;a(e,r,o)}function S(e,n,r){Papa.parse(e,{encoding:"UTF-8",complete:function(e){o(e);for(var r=[],a=[],i=[],s=0;s<e.data.length;s++){var l=!1,c=e.data[s];if(c.length&&1!==c.length){var u={name:c[0]&&""!==c[0]?c[0]:"--",favorite:!1,uri:null,password:null,username:null,notes:null};if(2===c.length)u.uri=t(c[1]);else if(3===c.length)u.uri=t(c[1]),u.username=c[2];else if(4===c.length)""===c[2]&&""===c[3]?(u.username=c[1],u.notes=c[2]+"\n"+c[3]):(u.username=c[2],u.notes=c[1]+"\n"+c[3]);else if(5===c.length)u.uri=t(c[1]),u.username=c[2],u.password=c[3],u.notes=c[4];else if(6===c.length)""===c[2]?(u.username=c[3],u.password=c[4],u.notes=c[5]):(u.username=c[2],u.password=c[3],u.notes=c[4]+"\n"+c[5]),u.uri=t(c[1]);else if(7===c.length)""===c[2]?(u.username=c[3],u.notes=c[4]+"\n"+c[6]):(u.username=c[2],u.notes=c[3]+"\n"+c[4]+"\n"+c[6]),u.uri=t(c[1]),u.password=c[5];else{u.notes="";for(var d=1;d<c.length;d++)if(u.notes=u.notes+c[d]+"\n","NO_TYPE"===c[d]){l=!0;break}}l||(""===u.username&&(u.username=null),""===u.password&&(u.password=null),""===u.notes&&(u.notes=null),""===u.uri&&(u.uri=null),a.push(u))}}n(r,a,i)}})}function C(e,t,o){function r(e,t,n){var o=e.find('> Groups > Group[ID="'+t+'"]');if(o.length){n&&""!==n&&(n=" > "+n),n=o.attr("Name")+n;return r(e,o.attr("ParentID"),n)}return n}function i(e){var a=$(e),i=a.find("root > Database");if(i.length){var d=i.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,S=null;if(h&&""!==h){var C=i.find('> Accounts > Account > LoginLinks > Login[SourceLoginID="'+h+'"]');if(C.length){var k=C.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&&(S=r(i,w,""));var P=s.length,I=l.length,T=S&&""!==S,A=T;if(T)for(u=0;u<s.length;u++)if(s[u].name===S){A=!1,P=u;break}var z={favorite:!1,uri:y&&""!==y?n(y):null,username:g&&""!==g?g:null,password:f&&""!==f?f:null,notes:b&&""!==b?b:null,name:v&&""!==v?v:"--"};if(l.push(z),A&&s.push({name:S}),T){var O={key:I,value:P};c.push(O)}}t(s,l,c)}else o()}var s=[],l=[],c=[],u=0;a(e,i,o)}function k(e,t,r){Papa.parse(e,{encoding:"UTF-8",complete:function(e){o(e);var r=[],a=[],i=[];angular.forEach(e.data,function(e,t){if(e.length>=3){var o=r.length,s=a.length,l=e[0]&&""!==e[0]&&"Unassigned"!==e[0],c=l,u=0;if(l)for(u=0;u<r.length;u++)if(r[u].name===e[0]){c=!1,o=u;break}var d={favorite:!1,uri:null,username:null,password:null,notes:"",name:e[2]&&""!==e[2]?e[2]:null};if("Web Logins"===e[1])d.uri=e[4]&&""!==e[4]?n(e[4]):null,d.username=e[5]&&""!==e[5]?e[5]:null,d.password=e[6]&&""!==e[6]?e[6]:null,d.notes=e[3]&&""!==e[3]?e[3].split("\\n").join("\n"):null;else if(e.length>3)for(var p=3;p<e.length;p++)e[p]&&""!==e[p]&&(""!==d.notes&&(d.notes=d.notes+"\n"),d.notes=d.notes+e[p]);if(e[1]&&""!==e[1]&&"Web Logins"!==e[1]&&(d.name=e[1]+": "+d.name),""===d.notes&&(d.notes=null),a.push(d),c&&r.push({name:e[0]}),l){var m={key:s,value:o};i.push(m)}}}),t(r,a,i)}})}function P(e,t,r){var a=[],i=[],s=[],l=["kind","autologin","favorite","hexcolor","protectedwithpassword","subdomainonly","type","tk_export_version","note","title","document_content"];Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e),angular.forEach(e.data,function(e,t){var o={favorite:!(!e.favorite||"true"!==e.favorite.toLowerCase()),uri:e.url&&""!==e.url?n(e.url):null,username:e.login&&""!==e.login?e.login:null,password:e.password&&""!==e.password?e.password:null,notes:e.memo&&""!==e.memo?e.memo:null,name:e.name&&""!==e.name?e.name:"--"};if("login"!==e.kind){o.name=e.title&&""!==e.title?e.title:"--",o.notes=e.note&&""!==e.note?e.note:null,o.notes||(o.notes=e.document_content&&""!==e.document_content?e.document_content:null);for(var r in e)e.hasOwnProperty(r)&&l.indexOf(r.toLowerCase())<0&&e[r]&&""!==e[r]&&(o.notes?o.notes+="\n":o.notes="",o.notes+=r+": "+e[r])}i.push(o)}),t(a,i,s)}})}function I(t,o,a){function i(t){var r=$(t),a=r.find("textarea"),i=a&&a.length?a.val():null,u=i?JSON.parse(i):null;if(u&&u.length)for(var d=0;d<u.length;d++){var p=u[d],m={favorite:!1,uri:null,username:null,password:null,notes:"",name:p.label&&""!==p.label?p.label.split(" ")[0]:"--"};if(p.data&&p.data.notes&&""!==p.data.notes&&(m.notes=p.data.notes.split("\\n").join("\n")),p.currentVersion&&p.currentVersion.fields)for(var g in p.currentVersion.fields)if(p.currentVersion.fields.hasOwnProperty(g)){var f=p.currentVersion.fields[g],h=f.actionType.toLowerCase();switch(h){case"password":m.password=f.value;break;case"email":case"username":case"user":case"name":m.username=f.value;break;case"url":m.uri=n(f.value);break;default:!m.username&&e(f.label,G)?m.username=f.value:!m.password&&e(f.label,K)?m.password=f.value:(m.notes&&""!==m.notes&&(m.notes=m.notes+"\n"),m.notes=m.notes+f.label+": "+f.value)}}""===m.notes&&(m.notes=null),l.push(m)}o(s,l,c)}var s=[],l=[],c=[];r(t,i,a)}function T(e,n,o){function a(e){var o=JSON.parse(e);if(o&&o.accounts)for(c=0;c<o.accounts.length;c++){var r=o.accounts[c],a={favorite:r.is_favorite&&!0===r.is_favorite,uri:r.domain&&""!==r.domain?t(r.domain):null,username:r.username&&""!==r.username?r.username:null,password:r.password&&""!==r.password?r.password:null,notes:null,name:r.label&&""!==r.label?r.label:r.domain};r.email&&""!==r.email&&(a.username&&""!==a.username?a.notes=r.email:a.username=r.email),a.name&&""!==a.name||(a.name="--"),s.push(a)}n(i,s,l)}var i=[],s=[],l=[],c=0;r(e,a,o)}function A(n,o,a){function i(n){var r=$(n.split("&shy;").join("").split("<WBR>").join("")),a=r.find("table.nobr");if(a.length)for(var i=0;i<a.length;i++){var u=$(a[i]),d={favorite:!1,uri:null,username:null,password:null,notes:"",name:u.find("span.caption").text()},p=u.find(".subcaption").text();p&&""!==p&&(d.uri=t(p));var m=[];if($.each(u.find("table td:not(.subcaption)"),function(e,t){$(t).find("br").replaceWith("\n");var n=$(t).text();""!==n&&m.push(n.split("\\n").join("\n"))}),m.length&&m.length%2==0)for(var g=0;g<m.length;g+=2){var f=m[g],h=m[g+1];!d.password&&e(f.replace(":",""),K)?d.password=h:!d.username&&e(f.replace(":",""),G)?d.username=h:(""!==d.notes&&(d.notes=d.notes+"\n"),d.notes=d.notes+f+" "+h)}d.notes&&""!==d.notes||(d.notes=null),d.name&&""!==d.name||(d.name="--"),l.push(d)}o(s,l,c)}var s=[],l=[],c=[];r(n,i,a)}function z(e,t,r){function a(e){var t=document.createElement("a");return t.href=e,t.hostname.startsWith("www.")?t.hostname.replace("www.",""):t.hostname}var i=[],s=[],l=[];Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e),angular.forEach(e.data,function(e,t){s.push({favorite:!1,uri:e.url&&""!==e.url?n(e.url):null,username:e.username&&""!==e.username?e.username:null,password:e.password&&""!==e.password?e.password:null,notes:e.notes&&""!==e.notes?e.notes:null,name:e.url&&""!==e.url?a(e.url):"--"})}),t(i,s,l)}})}function O(n,r,a){Papa.parse(n,{encoding:"UTF-8",complete:function(n){o(n);for(var a=[],i=[],s=[],l=0;l<n.data.length;l++){var c=n.data[l];if(!(c.length<2)){var u=c[c.length-1],d={name:c[0],favorite:!1,uri:null,password:null,username:null,notes:u&&""!==u?u:null};if(c.length>2&&c.length%2==0)for(var p=0;p<c.length-2;p+=2){var m=c[p+2],g=c[p+1];if(g&&""!==g&&m&&""!==m){g.toLowerCase();!d.uri&&e(g,B)?d.uri=t(m):!d.username&&e(g,G)?d.username=m:!d.password&&e(g,K)?d.password=m:(d.notes?d.notes+="\n":d.notes="",d.notes+=g+": "+m)}}i.push(d)}}r(a,i,s)}})}function E(e,n,o){function a(e){var o=JSON.parse(e);if(o&&o.length)for(c=0;c<o.length;c++){var r=o[c],a={favorite:!1,uri:r.login_url&&""!==r.login_url?t(r.login_url):null,username:null,password:null,notes:"",name:r.name&&""!==r.name?r.name:"--"};if(r.identifiers){r.identifiers.notes&&""!==r.identifiers.notes&&(a.notes=r.identifiers.notes.split("\\r\\n").join("\n").split("\\n").join("\n"));for(var u in r.identifiers)if(r.identifiers.hasOwnProperty(u)){var d=r.identifiers[u];if("notes"===u||""===d||null===d)continue;"username"===u?a.username=d:"password"===u?a.password=d:(""!==a.notes&&(a.notes+="\n"),a.notes+=u+": "+d)}""===a.notes&&(a.notes=null),s.push(a)}}n(i,s,l)}var i=[],s=[],l=[],c=0;r(e,a,o)}function U(e,n,r){function a(e,t){if(e&&""!==e)for(var n=e.split(/(?:\r\n|\r|\n)/),o=0;o<n.length;o++){var r=n[o],a=r.indexOf(":");if(!(a<0)){var i=r.substring(0,a),s=r.length>a?r.substring(a+1):null;if(i&&""!==i&&s&&""!==s&&"SecretType"!==i){var l=i.toLowerCase();"user name"===l?t.username=s:"password"===l?t.password=s:(""!==t.notes&&(t.notes+="\n"),t.notes+=i+": "+s)}}}}Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e);var r=[],i=[],s=[];angular.forEach(e.data,function(e,n){var o=e.ChamberName,l=r.length,c=i.length,u=o&&""!==o,d=u,p=0;if(u)for(p=0;p<r.length;p++)if(r[p].name===o){d=!1,l=p;break}var m={favorite:!(!e.Favorite||"1"!==e.Favorite),uri:e["Secret URL"]&&""!==e["Secret URL"]?t(e["Secret URL"]):null,username:null,password:null,notes:e.Notes&&""!==e.Notes?e.Notes:"",name:e["Secret Name"]&&""!==e["Secret Name"]?e["Secret Name"]:"--"};if(a(e.SecretData,m),a(e.CustomData,m),""===m.notes&&(m.notes=null),e["Secret Name"]&&i.push(m),d&&r.push({name:o}),u){var g={
key:c,value:l};s.push(g)}}),n(r,i,s)}})}function F(e,n,r){Papa.parse(e,{encoding:"UTF-8",complete:function(e){function r(e,t,n){for(var o=e;o<t.length-3;o++)t[o]&&""!==t[o]&&(n.notes?""!==n.notes&&(n.notes+="\n"):n.notes="",n.notes+=t[o])}o(e);for(var a=[],i=[],s=[],l=1;l<e.data.length;l++)if(!(e.data[l].length<3)){var c=e.data[l],u=c[e.data.length-1],d=c[e.data.length-2],p=c[0],m=a.length,g=i.length,f=u&&""!==u&&"Unfiled"!==u,h=f,v=0;if(f)for(v=0;v<a.length;v++)if(a[v].name===u){h=!1,m=v;break}var y={favorite:!1,uri:null,username:null,password:null,notes:d,name:c[1]&&""!==c[1]?c[1]:"--"};if("Web Logins"===p||"Servers"===p||"Email Accounts"===p?(y.uri=c[4]&&""!==c[4]?t(c[4]):null,y.username=c[2]&&""!==c[2]?c[2]:null,y.password=c[3]&&""!==c[3]?c[3]:null,r(5,c,y)):c.length>2&&r(2,c,y),y.name&&"--"!==y.name&&"Web Logins"!==p&&"Servers"!==p&&"Email Accounts"!==p&&(y.name=p+": "+y.name),""===y.notes&&(y.notes=null),i.push(y),h&&a.push({name:u}),f){var b={key:g,value:m};s.push(b)}}n(a,i,s)}})}function x(e,n,r){Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e);for(var r=[],a=[],i=[],s=0;s<e.data.length;s++){var l=e.data[s],c={name:l.DisplayName&&""!==l.DisplayName?l.DisplayName:"--",favorite:!1,uri:l.Url&&""!==l.Url?t(l.Url):null,password:l.Password&&""!==l.Password?l.Password:null,username:l.UserName&&""!==l.UserName?l.UserName:null,notes:l.Notes&&""!==l.Notes?l.Notes:null};a.push(c)}n(r,a,i)}})}function D(e,n,r){function a(e,t){var n=t[e]||t[" "+e];return n&&""!==n?n:null}Papa.parse(e,{header:!0,encoding:"UTF-8",complete:function(e){o(e);var r=[],i=[],s=[];angular.forEach(e.data,function(e,n){var o=r.length,l=i.length,c=!!a("category",e),u=c,d=0;if(c)for(d=0;d<r.length;d++)if(r[d].name===a("category",e)){u=!1,o=d;break}var p={favorite:!1,uri:a("site",e)?t(a("site",e)):null,username:a("username",e)?a("username",e):null,password:a("password",e)?a("password",e):null,notes:a("description",e)?a("description",e):null,name:a("title",e)?a("title",e):"--"};if(a("password2",e)&&(p.notes?p.notes+="\n":p.notes="",p.notes+="Password 2: "+a("password2",e)),i.push(p),u&&r.push({name:a("category",e)}),c){var m={key:l,value:o};s.push(m)}}),n(r,i,s)}})}function L(e,n,o){function a(e){var o=JSON.parse(e),r=0,a=0;if(o&&Object.keys(o).length)for(var u in o)if(o.hasOwnProperty(u)&&o[u].length)for(r=i.length,i.push({name:u}),c=0;c<o[u].length;c++){var d=o[u][c];if(d.display_name&&0===d.display_name.indexOf("http")){a=s.length;var p={favorite:!1,uri:t(d.display_name),username:d.attributes.username_value&&""!==d.attributes.username_value?d.attributes.username_value:null,password:d.secret&&""!==d.secret?d.secret:null,notes:"",name:d.display_name.replace("http://","").replace("https://","")};p.name>30&&(p.name=p.name.substring(0,30));for(var m in d.attributes)d.attributes.hasOwnProperty(m)&&"username_value"!==m&&"xdg:schema"!==m&&(""!==p.notes&&(p.notes+="\n"),p.notes+=m+": "+d.attributes[m]);""===p.notes&&(p.notes=null),s.push(p),l.push({key:a,value:r})}}n(i,s,l)}var i=[],s=[],l=[],c=0;r(e,a,o)}var M={};M.import=function(e,t,n,o){if(!t)return void o();switch(e){case"bitwardencsv":i(t,n,o);break;case"lastpass":s(t,n,o);break;case"safeincloudxml":l(t,n,o);break;case"keepass2xml":u(t,n,o);break;case"keepassxcsv":d(t,n,o);break;case"padlockcsv":c(t,n,o);break;case"1password1pif":p(t,n,o);break;case"1password6wincsv":m(t,n,o);break;case"chromecsv":case"vivaldicsv":case"operacsv":g(t,n,o);break;case"firefoxpasswordexportercsvxml":f(t,n,o);break;case"upmcsv":h(t,n,o);break;case"keepercsv":v(t,n,o);break;case"passworddragonxml":y(t,n,o);break;case"enpasscsv":b(t,n,o);break;case"pwsafexml":w(t,n,o);break;case"dashlanecsv":S(t,n,o);break;case"stickypasswordxml":C(t,n,o);break;case"msecurecsv":k(t,n,o);break;case"truekeycsv":P(t,n,o);break;case"clipperzhtml":I(t,n,o);break;case"avirajson":T(t,n,o);break;case"roboformhtml":A(t,n,o);break;case"saferpasscsv":z(t,n,o);break;case"ascendocsv":O(t,n,o);break;case"passwordbossjson":E(t,n,o);break;case"zohovaultcsv":U(t,n,o);break;case"splashidcsv":F(t,n,o);break;case"meldiumcsv":x(t,n,o);break;case"passkeepcsv":D(t,n,o);break;case"gnomejson":L(t,n,o);break;default:o()}};var K=["password","pass word","passphrase","pass phrase","pass","code","code word","codeword","secret","secret word","key","keyword","key word","keyphrase","key phrase","form_pw","wppassword","pin","pwd","pw","pword","passwd","p","serial","serial#","license key","reg #","passwort"],G=["user","name","user name","username","login name","email","e-mail","id","userid","user id","login","form_loginname","wpname","mail","loginid","login id","log","first name","last name","card#","account #","member","member #","nom","benutzername"],B=["url","hyper link","hyperlink","link","host","hostname","host name","server","address","hyper ref","href","web","website","web site","site","web-site","ort","adresse"];return M}),angular.module("bit.services").factory("passwordService",function(){function e(t,n){var o=0,r=n-t,a=Math.ceil(Math.log2(r));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++)o+=l[u]*Math.pow(2,c),c-=8;return o&=s,o>=r?e(t,n):t+o}var t={};return t.generatePassword=function(t){var n={length:10,ambiguous:!1,number:!0,minNumber:1,uppercase:!0,minUppercase:1,lowercase:!0,minLowercase:1,special:!1,minSpecial:1},o=angular.extend({},n,t);o.uppercase&&o.minUppercase<0&&(o.minUppercase=1),o.lowercase&&o.minLowercase<0&&(o.minLowercase=1),o.number&&o.minNumber<0&&(o.minNumber=1),o.special&&o.minSpecial<0&&(o.minSpecial=1),(!o.length||o.length<1)&&(o.length=10);var r=o.minUppercase+o.minLowercase+o.minNumber+o.minSpecial;o.length<r&&(o.length=r);var a=[];if(o.lowercase&&o.minLowercase>0)for(var i=0;i<o.minLowercase;i++)a.push("l");if(o.uppercase&&o.minUppercase>0)for(var s=0;s<o.minUppercase;s++)a.push("u");if(o.number&&o.minNumber>0)for(var l=0;l<o.minNumber;l++)a.push("n");if(o.special&&o.minSpecial>0)for(var c=0;c<o.minSpecial;c++)a.push("s");for(;a.length<o.length;)a.push("a");a.sort(function(){return 2*e(0,1)-1});var u="",d="abcdefghijkmnopqrstuvwxyz";o.ambiguous&&(d+="l"),o.lowercase&&(u+=d);var p="ABCDEFGHIJKLMNPQRSTUVWXYZ";o.ambiguous&&(p+="O"),o.uppercase&&(u+=p);var m="23456789";o.ambiguous&&(m+="01"),o.number&&(u+=m);o.special&&(u+="!@#$%^&*");for(var g="",f=0;f<o.length;f++){var h;switch(a[f]){case"l":h=d;break;case"u":h=p;break;case"n":h=m;break;case"s":h="!@#$%^&*";break;case"a":h=u}var v=e(0,h.length-1);g+=h.charAt(v)}return g},t}),angular.module("bit.services").factory("tokenService",["$sessionStorage","$localStorage","jwtHelper",function(e,t,n){var o={},r=null,a=null;return o.setToken=function(t){e.accessToken=t,r=t},o.getToken=function(){return r||(r=e.accessToken),r||null},o.clearToken=function(){r=null,delete e.accessToken},o.setRefreshToken=function(t){e.refreshToken=t,a=t},o.getRefreshToken=function(){return a||(a=e.refreshToken),a||null},o.clearRefreshToken=function(){a=null,delete e.refreshToken},o.setTwoFactorToken=function(e,n){t.twoFactor||(t.twoFactor={}),t.twoFactor[n]=e},o.getTwoFactorToken=function(e){return t.twoFactor?t.twoFactor[e]:null},o.clearTwoFactorToken=function(e){e?t.twoFactor&&t.twoFactor[e]&&delete t.twoFactor[e]:delete t.twoFactor},o.clearTokens=function(){o.clearToken(),o.clearRefreshToken()},o.tokenSecondsRemaining=function(e,t){var o=n.getTokenExpirationDate(e);if(t=t||0,null===o)return 0;var r=o.valueOf()-((new Date).valueOf()+1e3*t);return Math.round(r/1e3)},o.tokenNeedsRefresh=function(e,t){return t=t||5,o.tokenSecondsRemaining(e)<60*t},o}]),angular.module("bit.services").factory("validationService",function(){var e={};return e.addErrors=function(t,n){var o=n.data;if(t.$errors=[],!o||!angular.isObject(o))return void t.$errors.push("An unexpected error has occurred.");if(o&&o.ErrorModel&&(o=o.ErrorModel),!o.ValidationErrors)return void(o.Message?t.$errors.push(o.Message):t.$errors.push("An unexpected error has occurred."));for(var r in o.ValidationErrors)if(o.ValidationErrors.hasOwnProperty(r))for(var a=0;a<o.ValidationErrors[r].length;a++)e.addError(t,r,o.ValidationErrors[r][a])},e.addError=function(e,t,n,o){!o&&e.$errors||(e.$errors=[]);for(var r=!0,a=0;a<e.$errors.length;a++)if(e.$errors[a]===n){r=!1;break}r&&e.$errors.push(n),t&&""!==t&&e[t]&&e[t].$registerApiError&&e[t].$registerApiError()},e}),angular.module("bit.tools").controller("toolsController",["$scope","$uibModal","apiService","toastr","authService",function(e,t,n,o,r){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","authService","$uibModalInstance","cryptoService","cipherService","$q","toastr","$analytics",function(e,t,n,o,r,a,i,s,l){function c(){var e=new Date;return"bitwarden_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+="",e.length>=t?e:new Array(t-e.length+1).join(n)+e}l.eventTrack("toolsExportController",{category:"Modal"}),e.export=function(n){e.startedExport=!0;var o=[],r=[],u=t.folders.list({},function(e){r=a.decryptFolders(e.Data)}).$promise,d=t.logins.list({},function(e){o=a.decryptLogins(e.Data)}).$promise;i.all([u,d]).then(function(){if(!o.length)return s.error("Nothing to export.","Error!"),void e.close();for(var t={},n=0;n<r.length;n++)t[r[n].id]=r[n];try{var a=[];for(n=0;n<o.length;n++){var i={name:o[n].name,uri:o[n].uri,username:o[n].username,password:o[n].password,notes:o[n].notes,folder:o[n].folderId&&o[n].folderId in t?t[o[n].folderId].name:null,favorite:o[n].favorite?1:null,totp:o[n].totp};a.push(i)}var u=Papa.unparse(a),d=new Blob([u]);if(window.navigator.msSaveOrOpenBlob)window.navigator.msSaveBlob(d,c());else{var p=window.document.createElement("a");p.href=window.URL.createObjectURL(d,{type:"text/plain"}),p.download=c(),document.body.appendChild(p),p.click(),document.body.removeChild(p)}l.eventTrack("Exported Data"),s.success("Your data has been exported. Check your browser's downloads folder.","Success!"),e.close()}catch(t){s.error("Something went wrong. Please try again.","Error!"),e.close()}},function(){s.error("Something went wrong. Please try again.","Error!"),e.close()})},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.tools").controller("toolsImportController",["$scope","$state","apiService","$uibModalInstance","cryptoService","cipherService","toastr","importService","$analytics","$sce","validationService",function(e,t,n,o,r,a,i,s,l,c,u){function d(r,s,c){if(!r.length&&!s.length)return void m("Nothing was imported.");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("CSV data is not formatted correctly. Please check your import file and try again.")}n.ciphers.import({folders:a.encryptFolders(r),logins:a.encryptLogins(s),folderRelationships:c},function(){o.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)}function p(e){return!(null!==e.name&&"--"!==e.name||null!==e.password&&""!==e.password)}function m(t){if(l.eventTrack("Import Data Failed",{label:e.model.source}),o.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 r="";for(var a in n.ValidationErrors)if(n.ValidationErrors.hasOwnProperty(a))for(var s=0;s<n.ValidationErrors[a].length;s++)r+=a+": "+n.ValidationErrors[a][s]+" ";if(""!==r)return void i.error(r)}i.error("Something went wrong. Try again.","Oh No!")}l.eventTrack("toolsImportController",{category:"Modal"}),e.model={source:""},e.source={},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.')},{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)return void u.addError(n,"source","Select the format of the import file.",!0);var o=document.getElementById("file").files[0];if(!(o||t.fileContents&&""!==t.fileContents))return void u.addError(n,"file","Select the import file or copy/paste the import file contents.",!0);e.processing=!0,s.import(t.source,o||t.fileContents,d,m)},e.close=function(){o.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultAddFolderController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","$analytics",function(e,t,n,o,r,a){a.eventTrack("vaultAddFolderController",{category:"Modal"}),e.savePromise=null,e.save=function(o){var i=r.encryptFolder(o);e.savePromise=t.folders.post(i,function(e){a.eventTrack("Created Folder");var t=r.decryptFolder(e);n.close(t)}).$promise},e.close=function(){n.dismiss("close")}}]),angular.module("bit.vault").controller("vaultAddLoginController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","selectedFolder","$analytics","checkedFavorite","$rootScope","authService","$uibModal",function(e,t,n,o,r,a,i,s,l,c,u,d){function p(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("vaultAddLoginController",{category:"Modal"}),e.folders=c.vaultFolders,e.login={folderId:i?i.id:null,favorite:!0===l},u.getUserProfile().then(function(t){e.useTotp=t.premium}),e.savePromise=null,e.save=function(o){var a=r.encryptLogin(o);e.savePromise=t.logins.post(a,function(e){s.eventTrack("Created Login");var t=r.decryptLogin(e);n.close(t)}).$promise},e.generatePassword=function(){e.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Add"),e.login.password=a.generatePassword({length:12,special:!0}))},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.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("vaultAttachmentsController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","loginId","$analytics","validationService","toastr","$timeout","authService","$uibModal",function(e,t,n,o,r,a,i,s,l,c,u,d){function p(){return e.login.organizationId?o.getOrgKey(e.login.organizationId):null}i.eventTrack("vaultAttachmentsController",{category:"Modal"}),e.login={},e.readOnly=!0,e.loading=!0,e.isPremium=!0,e.canUseAttachments=!0;var m=!1;u.getUserProfile().then(function(n){return e.isPremium=n.premium,t.logins.get({id:a}).$promise}).then(function(t){e.login=r.decryptLogin(t),e.readOnly=!t.Edit,e.canUseAttachments=e.isPremium||e.login.organizationId,e.loading=!1},function(){e.loading=!1}),e.save=function(n){var o=document.getElementById("file"),l=o.files;if(!l||!l.length)return void s.addError(n,"file","Select a file.",!0);e.savePromise=r.encryptAttachmentFile(p(),l[0]).then(function(e){var n=new FormData,o=new Blob([e.data],{type:"application/octet-stream"});return n.append("data",o,e.fileName),t.ciphers.postAttachment({id:a},n).$promise}).then(function(t){i.eventTrack("Added Attachment"),e.login=r.decryptLogin(t),o.type="",o.type="file",o.value=""},function(e){e?s.addError(n,"file",e,!0):s.addError(n,"file","Something went wrong.",!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.");r.downloadAndDecryptAttachment(p(),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.login.attachments.indexOf(n);t>-1&&e.login.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,o,r){m||(t.preventDefault(),m=!0,n.close(!!e.login.attachments&&e.login.attachments.length>0))}),e.showUpgrade=function(){d.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})}}]),angular.module("bit.vault").controller("vaultController",["$scope","$uibModal","apiService","$filter","cryptoService","authService","toastr","cipherService","$q","$localStorage","$timeout","$rootScope","$state","$analytics",function(e,t,n,o,r,a,i,s,l,c,u,d,p,m){function g(){var t=n.folders.list({},function(e){for(var t=[{id:null,name:"No Folder"}],n=0;n<e.Data.length;n++){var o=s.decryptFolderPreview(e.Data[n]);t.push(o)}f(t)}).$promise,o=n.ciphers.list({},function(e){for(var n=[],o=0;o<e.Data.length;o++)if(1===e.Data[o].Type){var r=s.decryptLoginPreview(e.Data[o]);n.push(r)}l.when(t).then(function(){h(n)})}).$promise;l.all([o,t]).then(function(){e.loading=!1})}function f(e){d.vaultFolders=o("orderBy")(e,b)}function h(t){angular.forEach(d.vaultFolders,function(e,n){e.collapsed=c.collapsedFolders&&(e.id||"none")in c.collapsedFolders,angular.forEach(t,function(t){t.favorite?t.sort=-1:t.folderId==e.id&&(t.sort=n)})}),d.vaultLogins=e.logins=o("orderBy")(t,["sort","name","username"]);var n=y(d.vaultLogins,400);if(n.length>0){e.logins=n[0];var r=200;angular.forEach(n,function(t,n){r+=200,n>0&&u(function(){Array.prototype.push.apply(e.logins,t)},r)})}}function v(){d.vaultLogins=e.logins=o("orderBy")(d.vaultLogins,["name","username"])}function y(e,t){for(var n=[],o=0,r=e.length;o<r;)n.push(e.slice(o,o+=t));return n}function b(e){return e.id?e.name.toLowerCase():""}function w(e,t,n){return n.indexOf(e)===t}function S(){return $('input[name="loginSelection"]:checked').map(function(){return $(this).val()}).get().filter(w)}function C(e){$('input[name="loginSelection"]').prop("checked",e)}function k(t){var n=d.vaultLogins.indexOf(t);n>-1&&d.vaultLogins.splice(n,1),(n=e.logins.indexOf(t))>-1&&e.logins.splice(n,1)}e.loading=!0,e.logins=[],e.favoriteCollapsed=c.collapsedFolders&&"favorite"in c.collapsedFolders,e.folderIdFilter=void 0,p.params.refreshFromServer&&(d.vaultFolders=d.vaultLogins=null),e.$on("$viewContentLoaded",function(){if(d.vaultFolders&&d.vaultLogins)return e.loading=!1,f(d.vaultFolders),void h(d.vaultLogins);g()}),e.clipboardError=function(e){alert("Your web browser does not support easy clipboard copying. Edit the login and copy it manually instead.")},e.collapseExpand=function(e,t){c.collapsedFolders||(c.collapsedFolders={});var n=t?"favorite":e.id||"none";n in c.collapsedFolders?delete c.collapsedFolders[n]:c.collapsedFolders[n]=!0},e.editLogin=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultEditLogin.html",controller:"vaultEditLoginController",resolve:{loginId:function(){return e.id}}}).result.then(function(t){"edit"===t.action?(e.folderId=t.data.folderId,e.name=t.data.name,e.username=t.data.username,e.password=t.data.password,e.favorite=t.data.favorite,v()):"partialEdit"===t.action?(e.folderId=t.data.folderId,e.favorite=t.data.favorite):"delete"===t.action&&k(e)})},e.$on("vaultAddLogin",function(t,n){e.addLogin()}),e.addLogin=function(e,n){t.open({animation:!0,templateUrl:"app/vault/views/vaultAddLogin.html",controller:"vaultAddLoginController",resolve:{selectedFolder:function(){return e},checkedFavorite:function(){return n}}}).result.then(function(e){d.vaultLogins.push(e),v()})},e.deleteLogin=function(e){confirm("Are you sure you want to delete this login ("+e.name+")?")&&n.logins.del({id:e.id},function(){m.eventTrack("Deleted Login"),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"})}if(!e.organizationId&&!r.getEncKey())return void i.error("You cannot use this feature until you update your encryption key.","Feature Unavailable");t.open({animation:!0,templateUrl:"app/vault/views/vaultAttachments.html",controller:"vaultAttachmentsController",resolve:{loginId:function(){return e.id}}}).result.then(function(t){e.hasAttachments=t})})},e.editFolder=function(e){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),f(d.vaultFolders)})},e.deleteFolder=function(e){confirm("Are you sure you want to delete this folder ("+e.name+")?")&&n.folders.del({id:e.id},function(){m.eventTrack("Deleted Folder");var t=d.vaultFolders.indexOf(e);t>-1&&d.vaultFolders.splice(t,1)})},e.canDeleteFolder=function(e){if(!e||!e.id||!d.vaultLogins)return!1;var t=o("filter")(d.vaultLogins,{folderId:e.id});return t&&0===t.length},e.share=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultShareLogin.html",controller:"vaultShareLoginController",resolve:{loginId:function(){return e.id}}}).result.then(function(t){e.organizationId=t})},e.collections=function(e){t.open({animation:!0,templateUrl:"app/vault/views/vaultLoginCollections.html",controller:"vaultLoginCollectionsController",resolve:{loginId:function(){return e.id}}}).result.then(function(t){t.collectionIds&&!t.collectionIds.length&&k(e)})},e.filterFolder=function(t){e.folderIdFilter=t.id,$.AdminLTE&&$.AdminLTE.layout&&u(function(){$.AdminLTE.layout.fix()},0)},e.clearFilters=function(){e.folderIdFilter=void 0,$.AdminLTE&&$.AdminLTE.layout&&u(function(){$.AdminLTE.layout.fix()},0)},e.folderFilter=function(t){return void 0===e.folderIdFilter||t.id===e.folderIdFilter},e.unselectAll=function(){C(!1)},e.selectFolder=function(e,t){$(t.currentTarget).closest(".box").find('input[name="loginSelection"]').prop("checked",!0)},e.select=function(e){var t=$(e.currentTarget).closest("tr").find('input[name="loginSelection"]');t.prop("checked",!t.prop("checked"))},e.bulkMove=function(){var e=S();if(0===e.length)return void alert("You have not selected anything.");t.open({
animation:!0,templateUrl:"app/vault/views/vaultMoveLogins.html",controller:"vaultMoveLoginsController",size:"sm",resolve:{ids:function(){return e}}}).result.then(function(t){for(var n=0;n<e.length;n++){var r=o("filter")(d.vaultLogins,{id:e[n]});r.length&&(r[0].folderId=t)}C(!1),v(),i.success("Items have been moved!")})},e.bulkDelete=function(){var t=S();if(0===t.length)return void alert("You have not selected anything.");confirm("Are you sure you want to delete the selected logins (total: "+t.length+")?")&&(e.bulkActionLoading=!0,n.ciphers.delMany({ids:t},function(){m.eventTrack("Bulk Deleted Logins");for(var n=0;n<t.length;n++){var r=o("filter")(d.vaultLogins,{id:t[n]});r.length&&r[0].edit&&k(r[0])}C(!1),e.bulkActionLoading=!1,i.success("Items have been deleted!")},function(){i.error("An error occurred."),e.bulkActionLoading=!1}))}}]),angular.module("bit.vault").controller("vaultEditFolderController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","folderId","$analytics",function(e,t,n,o,r,a,i){i.eventTrack("vaultEditFolderController",{category:"Modal"}),e.folder={},t.folders.get({id:a},function(t){e.folder=r.decryptFolder(t)}),e.savePromise=null,e.save=function(o){var s=r.encryptFolder(o);e.savePromise=t.folders.put({id:a},s,function(e){i.eventTrack("Edited Folder");var t=r.decryptFolder(e);n.close(t)}).$promise},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultEditLoginController",["$scope","apiService","$uibModalInstance","cryptoService","cipherService","passwordService","loginId","$analytics","$rootScope","authService","$uibModal",function(e,t,n,o,r,a,i,s,l,c,u){function d(e){var t=$(e.trigger).parent().prev();"text"===t.attr("type")&&t.select()}s.eventTrack("vaultEditLoginController",{category:"Modal"}),e.folders=l.vaultFolders,e.login={},e.readOnly=!1,c.getUserProfile().then(function(n){return e.useTotp=n.premium,t.logins.get({id:i}).$promise}).then(function(t){e.login=r.decryptLogin(t),e.readOnly=!t.Edit,e.useTotp=e.useTotp||e.login.organizationUseTotp}),e.save=function(o){if(e.readOnly)e.savePromise=t.ciphers.putPartial({id:i},{folderId:o.folderId,favorite:o.favorite},function(e){s.eventTrack("Partially Edited Login"),n.close({action:"partialEdit",data:{id:i,favorite:o.favorite,folderId:o.folderId&&""!==o.folderId?o.folderId:null}})}).$promise;else{var a=r.encryptLogin(o);e.savePromise=t.logins.put({id:i},a,function(e){s.eventTrack("Edited Login");var t=r.decryptLogin(e);n.close({action:"edit",data:t})}).$promise}},e.generatePassword=function(){e.login.password&&!confirm("Are you sure you want to overwrite the current password?")||(s.eventTrack("Generated Password From Edit"),e.login.password=a.generatePassword({length:12,special:!0}))},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.folderSort=function(e){return e.id?e.name.toLowerCase():""},e.delete=function(){confirm("Are you sure you want to delete this login ("+e.login.name+")?")&&t.logins.del({id:e.login.id},function(){s.eventTrack("Deleted Login From Edit"),n.close({action:"delete",data:e.login.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("vaultLoginCollectionsController",["$scope","apiService","$uibModalInstance","cipherService","loginId","$analytics",function(e,t,n,o,r,a){a.eventTrack("vaultLoginCollectionsController",{category:"Modal"}),e.login={},e.readOnly=!1,e.loadingLogin=!0,e.loadingCollections=!0,e.selectedCollections={},e.collections=[],n.opened.then(function(){t.ciphers.getDetails({id:r}).$promise.then(function(t){if(e.loadingLogin=!1,e.readOnly=!t.Edit,t.Edit&&t.OrganizationId){1===t.Type&&(e.login=o.decryptLoginPreview(t));var n={};if(t.CollectionIds)for(var r=0;r<t.CollectionIds.length;r++)n[t.CollectionIds[r]]=!0;return e.selectedCollections=n,t}return null}).then(function(n){if(!n)return void(e.loadingCollections=!1);t.collections.listMe(function(t){for(var r=[],a=0;a<t.Data.length;a++)if(t.Data[a].OrganizationId!==n.OrganizationId||t.Data[a].ReadOnly)t.Data[a].Id in e.selectedCollections&&delete e.selectedCollections[t.Data[a].Id];else{var i=o.decryptCollection(t.Data[a]);r.push(i)}e.loadingCollections=!1,e.collections=r})})}),e.toggleCollectionSelectionAll=function(t){var n={};if(t.target.checked)for(var o=0;o<e.collections.length;o++)n[e.collections[o].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 o={collectionIds:[]};for(var i in e.selectedCollections)e.selectedCollections.hasOwnProperty(i)&&o.collectionIds.push(i);e.submitPromise=t.ciphers.putCollections({id:r},o).$promise.then(function(e){a.eventTrack("Edited Login Collections"),n.close({action:"collectionsEdit",collectionIds:o.collectionIds})})},e.close=function(){n.dismiss("cancel")}}]),angular.module("bit.vault").controller("vaultMoveLoginsController",["$scope","apiService","$uibModalInstance","ids","$analytics","$rootScope",function(e,t,n,o,r,a){r.eventTrack("vaultMoveLoginsController",{category:"Modal"}),e.folders=a.vaultFolders,e.count=o.length,e.save=function(){e.savePromise=t.ciphers.moveMany({ids:o,folderId:e.folderId},function(){r.eventTrack("Bulk Moved Logins"),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("vaultShareLoginController",["$scope","apiService","$uibModalInstance","authService","cipherService","loginId","$analytics","$state","cryptoService","$q","toastr",function(e,t,n,o,r,a,i,s,l,c,u){i.eventTrack("vaultShareLoginController",{category:"Modal"}),e.model={},e.login={},e.collections=[],e.selectedCollections={},e.organizations=[];var d={};e.loadingCollections=!0,e.loading=!0,e.readOnly=!1,t.logins.get({id:a}).$promise.then(function(t){return e.readOnly=!t.Edit,t.Edit&&(e.login=r.decryptLogin(t)),t.Edit}).then(function(t){if(e.loading=!1,t)return o.getUserProfile()}).then(function(n){if(n&&n.organizations){var o=[],a=!1;for(var i in n.organizations)n.organizations.hasOwnProperty(i)&&n.organizations[i].enabled&&(o.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=o,t.collections.listMe(function(t){for(var n=[],o=0;o<t.Data.length;o++)if(!t.Data[o].ReadOnly){var a=r.decryptCollection(t.Data[o]);a.organizationId=t.Data[o].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 o=0;o<e.collections.length;o++)e.model.organizationId&&e.collections[o].organizationId===e.model.organizationId&&!e.collections[o].readOnly&&(n[e.collections[o].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(o){var s=l.getOrgKey(o.organizationId),d=!1,p=[];if(e.login.attachments)for(var m=0;m<e.login.attachments.length;m++)!function(e){var n=r.downloadAndDecryptAttachment(null,e,!1).then(function(e){return l.encryptToBytes(e.buffer,s)}).then(function(n){if(!d){var r=new FormData,i=new Blob([n],{type:"application/octet-stream"}),c=l.encrypt(e.fileName,s);return r.append("data",i,c),t.ciphers.postShareAttachment({id:a,attachmentId:e.id,orgId:o.organizationId},r).$promise}},function(e){d=!0});p.push(n)}(e.login.attachments[m]);e.submitPromise=c.all(p).then(function(){if(!d){e.login.organizationId=o.organizationId;var n={collectionIds:[],cipher:r.encryptLogin(e.login,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 Login"),u.success("Login has been shared."),n.close(o.organizationId)})},e.close=function(){n.dismiss("cancel")},e.createOrg=function(){s.go("backend.user.settingsCreateOrg").then(function(){n.dismiss("cancel")})}}]),angular.module("bit.vault").controller("vaultSharedController",["$scope","apiService","cipherService","$analytics","$q","$localStorage","$uibModal","$filter","$rootScope","authService","cryptoService",function(e,t,n,o,r,a,i,s,l,c,u){function d(e){if(l.vaultLogins){var t=s("filter")(l.vaultLogins,{id:e.id});if(t&&t.length)return t[0]}return null}function p(e){if(e&&e.id){var t=l.vaultLogins.indexOf(e);t>-1&&l.vaultLogins.splice(t,1)}}e.logins=[],e.collections=[],e.loading=!0,e.$on("$viewContentLoaded",function(){var o=t.collections.listMe({},function(t){for(var o=[],r=0;r<t.Data.length;r++){var i=n.decryptCollection(t.Data[r],null,!0);i.collapsed=a.collapsedCollections&&i.id in a.collapsedCollections,o.push(i)}e.collections=o}).$promise,i=t.ciphers.listDetails({},function(t){for(var o=[],r=0;r<t.Data.length;r++)if(1===t.Data[r].Type){var i=n.decryptLoginPreview(t.Data[r]);o.push(i)}o.length&&e.collections.push({id:null,name:"Unassigned",collapsed:a.collapsedCollections&&"unassigned"in a.collapsedCollections}),e.logins=o}).$promise;r.all([o,i]).then(function(){e.loading=!1})}),e.clipboardError=function(e){alert("Your web browser does not support easy clipboard copying. Edit the login and copy it manually instead.")},e.attachments=function(e){c.getUserProfile().then(function(t){return{isPremium:t.premium,orgUseStorage:e.organizationId&&!!t.organizations[e.organizationId].maxStorageGb}}).then(function(t){return e.organizationId&&!t.orgUseStorage?void i.open({animation:!0,templateUrl:"app/views/paidOrgRequired.html",controller:"paidOrgRequiredController",resolve:{orgId:function(){return e.organizationId}}}):e.organizationId||t.isPremium?e.organizationId||u.getEncKey()?void i.open({animation:!0,templateUrl:"app/vault/views/vaultAttachments.html",controller:"vaultAttachmentsController",resolve:{loginId:function(){return e.id}}}).result.then(function(t){e.hasAttachments=t}):void toastr.error("You cannot use this feature until you update your encryption key.","Feature Unavailable"):void i.open({animation:!0,templateUrl:"app/views/premiumRequired.html",controller:"premiumRequiredController"})})},e.filterByCollection=function(e){return function(t){return t.collectionIds&&t.collectionIds.length?t.collectionIds.indexOf(e.id)>-1:null===e.id}},e.collectionSort=function(e){return e.id?e.name.toLowerCase():""},e.collapseExpand=function(e){a.collapsedCollections||(a.collapsedCollections={});var t=e.id||"unassigned";t in a.collapsedCollections?delete a.collapsedCollections[t]:a.collapsedCollections[t]=!0},e.editLogin=function(t){i.open({animation:!0,templateUrl:"app/vault/views/vaultEditLogin.html",controller:"vaultEditLoginController",resolve:{loginId:function(){return t.id}}}).result.then(function(n){var o=d(t)||{};if("edit"===n.action)t.folderId=o.folderId=n.data.folderId,t.name=o.name=n.data.name,t.username=o.username=n.data.username,t.password=o.username=n.data.password,t.favorite=o.favorite=n.data.favorite;else if("partialEdit"===n.action)t.folderId=o.folderId=n.data.folderId,t.favorite=o.favorite=n.data.favorite;else if("delete"===n.action){var r=e.logins.indexOf(t);r>-1&&e.logins.splice(r,1),p(o)}})},e.editCollections=function(e){i.open({animation:!0,templateUrl:"app/vault/views/vaultLoginCollections.html",controller:"vaultLoginCollectionsController",resolve:{loginId:function(){return e.id}}}).result.then(function(t){t.collectionIds&&(e.collectionIds=t.collectionIds)})},e.removeLogin=function(e,n){if(confirm("Are you sure you want to remove this login ("+e.name+") from the collection ("+n.name+") ?")){for(var r={collectionIds:[]},a=0;a<e.collectionIds.length;a++)e.collectionIds[a]!==n.id&&r.collectionIds.push(e.collectionIds[a]);t.ciphers.putCollections({id:e.id},r).$promise.then(function(t){o.eventTrack("Removed From Collection"),e.collectionIds=r.collectionIds})}}}]);