From 138e5a0b1ebc7d21c1f2a73c9742cef600c5af40 Mon Sep 17 00:00:00 2001 From: unarist Date: Sat, 24 Jun 2017 21:03:52 +0900 Subject: Fix webpack config for Windows (#3926) --- config/webpack/loaders/babel.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'config') diff --git a/config/webpack/loaders/babel.js b/config/webpack/loaders/babel.js index c23aa9375..ae65db9eb 100644 --- a/config/webpack/loaders/babel.js +++ b/config/webpack/loaders/babel.js @@ -1,7 +1,7 @@ module.exports = { test: /\.js$/, // include react-intl because transform-react-remove-prop-types needs to apply to it - exclude: /node_modules\/(?!react-intl)/, + exclude: /node_modules[\/\\](?!react-intl)/, loader: 'babel-loader', options: { forceEnv: process.env.NODE_ENV || 'development', -- cgit From 68dca26a5d36eacb7d7e691635a14b6562ba7cf1 Mon Sep 17 00:00:00 2001 From: unarist Date: Sun, 25 Jun 2017 19:49:53 +0900 Subject: Fix react-intl/locale-data import issue on production build (#3937) Webpack seems to fail to import `react-intl/locale-data/*.js` if those files has been proceed by babel, and this also breaks applying our translation. Note that this won't be a problem on English locale, because react-intl includes it as default and works fine without manually added locale-data. Also this issue seems to only occurs on production build, but I'm not sure about reason. --- config/webpack/loaders/babel.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'config') diff --git a/config/webpack/loaders/babel.js b/config/webpack/loaders/babel.js index ae65db9eb..a1992a450 100644 --- a/config/webpack/loaders/babel.js +++ b/config/webpack/loaders/babel.js @@ -1,7 +1,10 @@ module.exports = { test: /\.js$/, // include react-intl because transform-react-remove-prop-types needs to apply to it - exclude: /node_modules[\/\\](?!react-intl)/, + exclude: { + test: /node_modules/, + exclude: /react-intl[\/\\](?!locale-data)/, + }, loader: 'babel-loader', options: { forceEnv: process.env.NODE_ENV || 'development', -- cgit From f7301bd5b94d3033b5dbb9ff65dd1ed8ac825ce5 Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Sun, 25 Jun 2017 16:54:30 +0200 Subject: Add overview of active sessions (#3929) * Add overview of active sessions * Better display of browser/platform name * Improve how browser information is stored and displayed for sessions overview * Fix test --- Gemfile | 1 + Gemfile.lock | 2 + app/controllers/auth/registrations_controller.rb | 5 +++ app/helpers/settings_helper.rb | 12 ++++++ app/javascript/styles/tables.scss | 12 ++++++ app/models/session_activation.rb | 48 +++++++++++++++------- app/models/user.rb | 6 ++- app/views/auth/registrations/_sessions.html.haml | 23 +++++++++++ app/views/auth/registrations/edit.html.haml | 4 ++ config/initializers/devise.rb | 2 +- config/locales/en.yml | 37 +++++++++++++++++ ...34742_add_description_to_session_activations.rb | 7 ++++ db/schema.rb | 5 ++- spec/rails_helper.rb | 2 +- yarn.lock | 11 +---- 15 files changed, 147 insertions(+), 30 deletions(-) create mode 100644 app/views/auth/registrations/_sessions.html.haml create mode 100644 db/migrate/20170624134742_add_description_to_session_activations.rb (limited to 'config') diff --git a/Gemfile b/Gemfile index 77fffe7a6..aecd82702 100644 --- a/Gemfile +++ b/Gemfile @@ -20,6 +20,7 @@ gem 'paperclip-av-transcoder', '~> 0.6' gem 'addressable', '~> 2.5' gem 'bootsnap' +gem 'browser' gem 'cld3', '~> 3.1' gem 'devise', '~> 4.2' gem 'devise-two-factor', '~> 3.0' diff --git a/Gemfile.lock b/Gemfile.lock index 00ce84556..627a01787 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -70,6 +70,7 @@ GEM bootsnap (1.0.0) msgpack (~> 1.0) brakeman (3.6.2) + browser (2.4.0) builder (3.2.3) bullet (5.5.1) activesupport (>= 3.0.0) @@ -483,6 +484,7 @@ DEPENDENCIES binding_of_caller (~> 0.7) bootsnap brakeman (~> 3.6) + browser bullet (~> 5.5) bundler-audit (~> 0.5) capistrano (~> 3.8) diff --git a/app/controllers/auth/registrations_controller.rb b/app/controllers/auth/registrations_controller.rb index d385c08e1..60ace04d7 100644 --- a/app/controllers/auth/registrations_controller.rb +++ b/app/controllers/auth/registrations_controller.rb @@ -5,6 +5,7 @@ class Auth::RegistrationsController < Devise::RegistrationsController before_action :check_enabled_registrations, only: [:new, :create] before_action :configure_sign_up_params, only: [:create] + before_action :set_sessions, only: [:edit, :update] def destroy not_found @@ -41,4 +42,8 @@ class Auth::RegistrationsController < Devise::RegistrationsController def determine_layout %w(edit update).include?(action_name) ? 'admin' : 'auth' end + + def set_sessions + @sessions = current_user.session_activations + end end diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb index 172ef33ca..847eff2e7 100644 --- a/app/helpers/settings_helper.rb +++ b/app/helpers/settings_helper.rb @@ -41,4 +41,16 @@ module SettingsHelper def hash_to_object(hash) HashObject.new(hash) end + + def session_device_icon(session) + device = session.detection.device + + if device.mobile? + 'mobile' + elsif device.tablet? + 'tablet' + else + 'desktop' + end + end end diff --git a/app/javascript/styles/tables.scss b/app/javascript/styles/tables.scss index f7def8cf3..6e54c59c0 100644 --- a/app/javascript/styles/tables.scss +++ b/app/javascript/styles/tables.scss @@ -42,6 +42,18 @@ strong { font-weight: 500; } + + &.inline-table { + td, + th { + padding: 8px 0; + } + + & > tbody > tr:nth-child(odd) > td, + & > tbody > tr:nth-child(odd) > th { + background: transparent; + } + } } samp { diff --git a/app/models/session_activation.rb b/app/models/session_activation.rb index 71e9f023c..75339b5f7 100644 --- a/app/models/session_activation.rb +++ b/app/models/session_activation.rb @@ -8,31 +8,49 @@ # session_id :string not null # created_at :datetime not null # updated_at :datetime not null +# user_agent :string default(""), not null +# ip :inet # class SessionActivation < ApplicationRecord - LIMIT = Rails.configuration.x.max_session_activations - - def self.active?(id) - id && where(session_id: id).exists? + def detection + @detection ||= Browser.new(user_agent) end - def self.activate(id) - activation = create!(session_id: id) - purge_old - activation + def browser + detection.id end - def self.deactivate(id) - return unless id - where(session_id: id).destroy_all + def platform + detection.platform.id end - def self.purge_old - order('created_at desc').offset(LIMIT).destroy_all + before_save do + self.user_agent = '' if user_agent.nil? end - def self.exclusive(id) - where('session_id != ?', id).destroy_all + class << self + def active?(id) + id && where(session_id: id).exists? + end + + def activate(options = {}) + activation = create!(options) + purge_old + activation + end + + def deactivate(id) + return unless id + where(session_id: id).destroy_all + end + + def purge_old + order('created_at desc').offset(Rails.configuration.x.max_session_activations).destroy_all + end + + def exclusive(id) + where('session_id != ?', id).destroy_all + end end end diff --git a/app/models/user.rb b/app/models/user.rb index fccf1089b..c31a0c644 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -91,8 +91,10 @@ class User < ApplicationRecord settings.auto_play_gif end - def activate_session - session_activations.activate(SecureRandom.hex).session_id + def activate_session(request) + session_activations.activate(session_id: SecureRandom.hex, + user_agent: request.user_agent, + ip: request.ip).session_id end def exclusive_session(id) diff --git a/app/views/auth/registrations/_sessions.html.haml b/app/views/auth/registrations/_sessions.html.haml new file mode 100644 index 000000000..11c0d4e31 --- /dev/null +++ b/app/views/auth/registrations/_sessions.html.haml @@ -0,0 +1,23 @@ +%h6= t 'sessions.title' +%p.muted-hint= t 'sessions.explanation' + +%table.table.inline-table + %thead + %tr + %th= t 'sessions.browser' + %th= t 'sessions.ip' + %th= t 'sessions.activity' + %tbody + - @sessions.each do |session| + %tr + %td + %span{ title: session.user_agent }= fa_icon session_device_icon(session) + = ' ' + = t 'sessions.description', browser: t("sessions.browsers.#{session.browser}"), platform: t("sessions.platforms.#{session.platform}") + %td + %samp= session.ip + %td + - if request.session['auth_id'] == session.session_id + = t 'sessions.current_session' + - else + %time.time-ago{ datetime: session.updated_at.iso8601, title: l(session.updated_at) }= l(session.updated_at) diff --git a/app/views/auth/registrations/edit.html.haml b/app/views/auth/registrations/edit.html.haml index 38d4349cb..fbc8d017b 100644 --- a/app/views/auth/registrations/edit.html.haml +++ b/app/views/auth/registrations/edit.html.haml @@ -12,6 +12,10 @@ .actions = f.button :button, t('generic.save_changes'), type: :submit +%hr/ + += render 'sessions' + - if open_deletion? %hr/ diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 6d3a73ef6..d51471d30 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -1,6 +1,6 @@ Warden::Manager.after_set_user except: :fetch do |user, warden| SessionActivation.deactivate warden.raw_session['auth_id'] - warden.raw_session['auth_id'] = user.activate_session + warden.raw_session['auth_id'] = user.activate_session(warden.request) end Warden::Manager.after_fetch do |user, warden| diff --git a/config/locales/en.yml b/config/locales/en.yml index 0d33aae3f..1d8e3f6b0 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -320,6 +320,43 @@ en: missing_resource: Could not find the required redirect URL for your account proceed: Proceed to follow prompt: 'You are going to follow:' + sessions: + activity: Last activity + browser: Browser + browsers: + alipay: Alipay + blackberry: Blackberry + chrome: Chrome + edge: Microsoft Edge + firefox: Firefox + generic: Unknown browser + ie: Internet Explorer + micro_messenger: MicroMessenger + nokia: Nokia S40 Ovi Browser + opera: Opera + phantom_js: PhantomJS + qq: QQ Browser + safari: Safari + uc_browser: UCBrowser + weibo: Weibo + current_session: Current session + description: "%{browser} on %{platform}" + explanation: These are the web browsers currently logged in to your Mastodon account. + ip: IP + platforms: + adobe_air: Adobe Air + android: Android + blackberry: Blackberry + chrome_os: ChromeOS + firefox_os: Firefox OS + ios: iOS + linux: Linux + mac: Mac + other: unknown platform + windows: Windows + windows_mobile: Windows Mobile + windows_phone: Windows Phone + title: Sessions settings: authorized_apps: Authorized apps back: Back to Mastodon diff --git a/db/migrate/20170624134742_add_description_to_session_activations.rb b/db/migrate/20170624134742_add_description_to_session_activations.rb new file mode 100644 index 000000000..9dbb15564 --- /dev/null +++ b/db/migrate/20170624134742_add_description_to_session_activations.rb @@ -0,0 +1,7 @@ +class AddDescriptionToSessionActivations < ActiveRecord::Migration[5.1] + def change + add_column :session_activations, :user_agent, :string, null: false, default: '' + add_column :session_activations, :ip, :inet + add_foreign_key :session_activations, :users, on_delete: :cascade + end +end diff --git a/db/schema.rb b/db/schema.rb index b6aceb930..1e7d6c0b3 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20170623152212) do +ActiveRecord::Schema.define(version: 20170624134742) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -255,6 +255,8 @@ ActiveRecord::Schema.define(version: 20170623152212) do t.string "session_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.string "user_agent", default: "", null: false + t.inet "ip" t.index ["session_id"], name: "index_session_activations_on_session_id", unique: true t.index ["user_id"], name: "index_session_activations_on_user_id" end @@ -404,6 +406,7 @@ ActiveRecord::Schema.define(version: 20170623152212) do add_foreign_key "reports", "accounts", column: "action_taken_by_account_id", on_delete: :nullify add_foreign_key "reports", "accounts", column: "target_account_id", on_delete: :cascade add_foreign_key "reports", "accounts", on_delete: :cascade + add_foreign_key "session_activations", "users", on_delete: :cascade add_foreign_key "statuses", "accounts", column: "in_reply_to_account_id", on_delete: :nullify add_foreign_key "statuses", "accounts", on_delete: :cascade add_foreign_key "statuses", "statuses", column: "in_reply_to_id", on_delete: :nullify diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 31c94b1e4..cfc9eec9e 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -23,7 +23,7 @@ Devise::Test::ControllerHelpers.module_eval do original_sign_in(resource, scope: scope) SessionActivation.deactivate warden.raw_session["auth_id"] - warden.raw_session["auth_id"] = resource.activate_session + warden.raw_session["auth_id"] = resource.activate_session(warden.request) end end diff --git a/yarn.lock b/yarn.lock index ef870d7e2..d1a1687a0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7184,16 +7184,7 @@ webpack-bundle-analyzer@^2.8.2: opener "^1.4.3" ws "^2.3.1" -webpack-dev-middleware@^1.10.2: - version "1.10.2" - resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-1.10.2.tgz#2e252ce1dfb020dbda1ccb37df26f30ab014dbd1" - dependencies: - memory-fs "~0.4.1" - mime "^1.3.4" - path-is-absolute "^1.0.0" - range-parser "^1.0.3" - -webpack-dev-middleware@^1.11.0: +webpack-dev-middleware@^1.10.2, webpack-dev-middleware@^1.11.0: version "1.11.0" resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-1.11.0.tgz#09691d0973a30ad1f82ac73a12e2087f0a4754f9" dependencies: -- cgit From 87efa3872193084468c25f410f5cf9189c0b976e Mon Sep 17 00:00:00 2001 From: amazedkoumei Date: Mon, 26 Jun 2017 01:13:31 +0900 Subject: more free pgconfig by .env (#3909) * more free pgconfig for streaming by .env * fix wrong default values * database.yml read ENV as same as streaming server --- config/database.yml | 8 ++++++++ streaming/index.js | 6 +++++- 2 files changed, 13 insertions(+), 1 deletion(-) (limited to 'config') diff --git a/config/database.yml b/config/database.yml index 39393e93a..079ea7b4a 100644 --- a/config/database.yml +++ b/config/database.yml @@ -7,6 +7,10 @@ default: &default development: <<: *default database: mastodon_development + username: <%= ENV['DB_USER'] %> + password: <%= ENV['DB_PASS'] %> + host: <%= ENV['DB_HOST'] %> + port: <%= ENV['DB_PORT'] %> # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". @@ -14,6 +18,10 @@ development: test: <<: *default database: mastodon_test<%= ENV['TEST_ENV_NUMBER'] %> + username: <%= ENV['TEST_DB_USER'] %> + password: <%= ENV['TEST_DB_PASS'] %> + host: <%= ENV['TEST_DB_HOST'] %> + port: <%= ENV['TEST_DB_PORT'] %> production: <<: *default diff --git a/streaming/index.js b/streaming/index.js index 156e1d4bc..701cb2f55 100644 --- a/streaming/index.js +++ b/streaming/index.js @@ -78,7 +78,11 @@ const startWorker = (workerId) => { const pgConfigs = { development: { - database: 'mastodon_development', + user: process.env.DB_USER || pg.defaults.user, + password: process.env.DB_PASS || pg.defaults.password, + database: process.env.DB_NAME || 'mastodon_development', + host: process.env.DB_HOST || pg.defaults.host, + port: process.env.DB_PORT || pg.defaults.port, max: 10, }, -- cgit From d821aba002002f79385abd7f052f68c383d5cd0c Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Sun, 25 Jun 2017 22:13:02 +0200 Subject: Rename "Credentials" page to "Security" for clarity (#3941) * Rename "Credentials" page to "Security" for clarity * Change "security" icon from cog to lock --- config/locales/en.yml | 2 +- config/navigation.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'config') diff --git a/config/locales/en.yml b/config/locales/en.yml index 1d8e3f6b0..7238949dc 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -200,7 +200,7 @@ en: applications: invalid_url: The provided URL is invalid auth: - change_password: Credentials + change_password: Security delete_account: Delete account delete_account_html: If you wish to delete your account, you can proceed here. You will be asked for confirmation. didnt_get_confirmation: Didn't receive confirmation instructions? diff --git a/config/navigation.rb b/config/navigation.rb index d7508f019..535d033f5 100644 --- a/config/navigation.rb +++ b/config/navigation.rb @@ -7,7 +7,7 @@ SimpleNavigation::Configuration.run do |navigation| primary.item :settings, safe_join([fa_icon('cog fw'), t('settings.settings')]), settings_profile_url do |settings| settings.item :profile, safe_join([fa_icon('user fw'), t('settings.edit_profile')]), settings_profile_url settings.item :preferences, safe_join([fa_icon('sliders fw'), t('settings.preferences')]), settings_preferences_url - settings.item :password, safe_join([fa_icon('cog fw'), t('auth.change_password')]), edit_user_registration_url, highlights_on: %r{/auth/edit|/settings/delete} + settings.item :password, safe_join([fa_icon('lock fw'), t('auth.change_password')]), edit_user_registration_url, highlights_on: %r{/auth/edit|/settings/delete} settings.item :two_factor_authentication, safe_join([fa_icon('mobile fw'), t('settings.two_factor_authentication')]), settings_two_factor_authentication_url, highlights_on: %r{/settings/two_factor_authentication} settings.item :import, safe_join([fa_icon('cloud-upload fw'), t('settings.import')]), settings_import_url settings.item :export, safe_join([fa_icon('cloud-download fw'), t('settings.export')]), settings_export_url -- cgit From 436ce03772c8c87a215cdcd88020edfb8c241d38 Mon Sep 17 00:00:00 2001 From: amazedkoumei Date: Mon, 26 Jun 2017 06:29:22 +0900 Subject: fix unnecessary variable (#3947) --- config/database.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'config') diff --git a/config/database.yml b/config/database.yml index 079ea7b4a..f74635a36 100644 --- a/config/database.yml +++ b/config/database.yml @@ -18,10 +18,10 @@ development: test: <<: *default database: mastodon_test<%= ENV['TEST_ENV_NUMBER'] %> - username: <%= ENV['TEST_DB_USER'] %> - password: <%= ENV['TEST_DB_PASS'] %> - host: <%= ENV['TEST_DB_HOST'] %> - port: <%= ENV['TEST_DB_PORT'] %> + username: <%= ENV['DB_USER'] %> + password: <%= ENV['DB_PASS'] %> + host: <%= ENV['DB_HOST'] %> + port: <%= ENV['DB_PORT'] %> production: <<: *default -- cgit From ed7dc1704dc3ce82567d9aac366b095f02ce181f Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Sun, 25 Jun 2017 23:51:32 +0200 Subject: Bind web UI access tokens to sessions (#3940) * Add overview of active sessions * Better display of browser/platform name * Improve how browser information is stored and displayed for sessions overview * Fix test * Fix #2347 - Bind web UI access token to session When you logout, session also destroys the access token, so it's no longer valid. If access token is destroyed some other way, the session is also destroyed, requiring a re-login. Fix #1681 - Add scheduler to remove revoked access tokens and grants * Fix test --- app/controllers/application_controller.rb | 5 +++ app/controllers/home_controller.rb | 12 +----- app/models/session_activation.rb | 44 +++++++++++++++++----- .../scheduler/doorkeeper_cleanup_scheduler.rb | 11 ++++++ config/sidekiq.yml | 3 ++ ...3_add_access_token_id_to_session_activations.rb | 6 +++ db/schema.rb | 4 +- 7 files changed, 63 insertions(+), 22 deletions(-) create mode 100644 app/workers/scheduler/doorkeeper_cleanup_scheduler.rb create mode 100644 db/migrate/20170625140443_add_access_token_id_to_session_activations.rb (limited to 'config') diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 9cb397aa8..865fcd125 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -11,6 +11,7 @@ class ApplicationController < ActionController::Base include UserTrackingConcern helper_method :current_account + helper_method :current_session helper_method :single_user_mode? rescue_from ActionController::RoutingError, with: :not_found @@ -68,6 +69,10 @@ class ApplicationController < ActionController::Base @current_account ||= current_user.try(:account) end + def current_session + @current_session ||= SessionActivation.find_by(session_id: session['auth_id']) + end + def cache_collection(raw, klass) return raw unless klass.respond_to?(:with_includes) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 1d41892cd..6209a3ae9 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -5,7 +5,7 @@ class HomeController < ApplicationController def index @body_classes = 'app-body' - @token = find_or_create_access_token.token + @token = current_session.token @web_settings = Web::Setting.find_by(user: current_user)&.data || {} @admin = Account.find_local(Setting.site_contact_username) @streaming_api_base_url = Rails.configuration.x.streaming_api_base_url @@ -16,14 +16,4 @@ class HomeController < ApplicationController def authenticate_user! redirect_to(single_user_mode? ? account_path(Account.first) : about_path) unless user_signed_in? end - - def find_or_create_access_token - Doorkeeper::AccessToken.find_or_create_for( - Doorkeeper::Application.where(superapp: true).first, - current_user.id, - Doorkeeper::OAuth::Scopes.from_string('read write follow'), - Doorkeeper.configuration.access_token_expires_in, - Doorkeeper.configuration.refresh_token_enabled? - ) - end end diff --git a/app/models/session_activation.rb b/app/models/session_activation.rb index 75339b5f7..02a918e8a 100644 --- a/app/models/session_activation.rb +++ b/app/models/session_activation.rb @@ -3,16 +3,23 @@ # # Table name: session_activations # -# id :integer not null, primary key -# user_id :integer not null -# session_id :string not null -# created_at :datetime not null -# updated_at :datetime not null -# user_agent :string default(""), not null -# ip :inet +# id :integer not null, primary key +# user_id :integer not null +# session_id :string not null +# created_at :datetime not null +# updated_at :datetime not null +# user_agent :string default(""), not null +# ip :inet +# access_token_id :integer # class SessionActivation < ApplicationRecord + belongs_to :access_token, class_name: 'Doorkeeper::AccessToken', dependent: :destroy + + delegate :token, + to: :access_token, + allow_nil: true + def detection @detection ||= Browser.new(user_agent) end @@ -25,9 +32,8 @@ class SessionActivation < ApplicationRecord detection.platform.id end - before_save do - self.user_agent = '' if user_agent.nil? - end + before_create :assign_access_token + before_save :assign_user_agent class << self def active?(id) @@ -53,4 +59,22 @@ class SessionActivation < ApplicationRecord where('session_id != ?', id).destroy_all end end + + private + + def assign_user_agent + self.user_agent = '' if user_agent.nil? + end + + def assign_access_token + superapp = Doorkeeper::Application.find_by(superapp: true) + + return if superapp.nil? + + self.access_token = Doorkeeper::AccessToken.create!(application_id: superapp.id, + resource_owner_id: user_id, + scopes: 'read write follow', + expires_in: Doorkeeper.configuration.access_token_expires_in, + use_refresh_token: Doorkeeper.configuration.refresh_token_enabled?) + end end diff --git a/app/workers/scheduler/doorkeeper_cleanup_scheduler.rb b/app/workers/scheduler/doorkeeper_cleanup_scheduler.rb new file mode 100644 index 000000000..6488798cd --- /dev/null +++ b/app/workers/scheduler/doorkeeper_cleanup_scheduler.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true +require 'sidekiq-scheduler' + +class Scheduler::DoorkeeperCleanupScheduler + include Sidekiq::Worker + + def perform + Doorkeeper::AccessToken.where('revoked_at IS NOT NULL').where('revoked_at < NOW()').delete_all + Doorkeeper::AccessGrant.where('revoked_at IS NOT NULL').where('revoked_at < NOW()').delete_all + end +end diff --git a/config/sidekiq.yml b/config/sidekiq.yml index 6ed0aa4b5..78aaa311c 100644 --- a/config/sidekiq.yml +++ b/config/sidekiq.yml @@ -15,3 +15,6 @@ feed_cleanup_scheduler: cron: '0 0 * * *' class: Scheduler::FeedCleanupScheduler + doorkeeper_cleanup_scheduler: + cron: '1 1 * * 0' + class: Scheduler::DoorkeeperCleanupScheduler diff --git a/db/migrate/20170625140443_add_access_token_id_to_session_activations.rb b/db/migrate/20170625140443_add_access_token_id_to_session_activations.rb new file mode 100644 index 000000000..213a77a83 --- /dev/null +++ b/db/migrate/20170625140443_add_access_token_id_to_session_activations.rb @@ -0,0 +1,6 @@ +class AddAccessTokenIdToSessionActivations < ActiveRecord::Migration[5.1] + def change + add_column :session_activations, :access_token_id, :integer + add_foreign_key :session_activations, :oauth_access_tokens, column: :access_token_id, on_delete: :cascade + end +end diff --git a/db/schema.rb b/db/schema.rb index 1e7d6c0b3..159704c6a 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20170624134742) do +ActiveRecord::Schema.define(version: 20170625140443) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -257,6 +257,7 @@ ActiveRecord::Schema.define(version: 20170624134742) do t.datetime "updated_at", null: false t.string "user_agent", default: "", null: false t.inet "ip" + t.integer "access_token_id" t.index ["session_id"], name: "index_session_activations_on_session_id", unique: true t.index ["user_id"], name: "index_session_activations_on_user_id" end @@ -406,6 +407,7 @@ ActiveRecord::Schema.define(version: 20170624134742) do add_foreign_key "reports", "accounts", column: "action_taken_by_account_id", on_delete: :nullify add_foreign_key "reports", "accounts", column: "target_account_id", on_delete: :cascade add_foreign_key "reports", "accounts", on_delete: :cascade + add_foreign_key "session_activations", "oauth_access_tokens", column: "access_token_id", on_delete: :cascade add_foreign_key "session_activations", "users", on_delete: :cascade add_foreign_key "statuses", "accounts", column: "in_reply_to_account_id", on_delete: :nullify add_foreign_key "statuses", "accounts", on_delete: :cascade -- cgit From 5e8d037e271bdd230fc7ab1e91bcee16ac87e0e1 Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Sun, 25 Jun 2017 23:51:46 +0200 Subject: Fix #3910 - Require OTP authentication to disable 2FA (#3935) * Fix #3910 - Require OTP authentication to disable 2FA. Also, remove ability to generate new OTP backup codes *after* initial backup codes were handed out during activation * Restore recovery code re-generation * Improve display of some 2FA elements --- .../two_factor_authentications_controller.rb | 20 ++++++++--- app/javascript/styles/admin.scss | 5 +++ app/javascript/styles/forms.scss | 1 - app/javascript/styles/lists.scss | 1 - .../recovery_codes/index.html.haml | 2 +- .../two_factor_authentications/show.html.haml | 42 +++++++++++++--------- config/locales/ca.yml | 2 +- config/locales/de.yml | 2 +- config/locales/en.yml | 8 +++-- config/locales/fa.yml | 2 +- config/locales/fr.yml | 2 +- config/locales/he.yml | 2 +- config/locales/id.yml | 2 +- config/locales/io.yml | 2 +- config/locales/ja.yml | 2 +- config/locales/nl.yml | 2 +- config/locales/no.yml | 2 +- config/locales/oc.yml | 6 ++-- config/locales/pl.yml | 2 +- config/locales/pt-BR.yml | 2 +- config/locales/ru.yml | 2 +- config/locales/th.yml | 2 +- config/locales/tr.yml | 2 +- config/locales/uk.yml | 2 +- config/locales/zh-CN.yml | 2 +- config/locales/zh-HK.yml | 2 +- .../two_factor_authentications_controller_spec.rb | 40 +++++++++++++++++---- 27 files changed, 108 insertions(+), 53 deletions(-) (limited to 'config') diff --git a/app/controllers/settings/two_factor_authentications_controller.rb b/app/controllers/settings/two_factor_authentications_controller.rb index f66c3a908..983483881 100644 --- a/app/controllers/settings/two_factor_authentications_controller.rb +++ b/app/controllers/settings/two_factor_authentications_controller.rb @@ -7,7 +7,9 @@ module Settings before_action :authenticate_user! before_action :verify_otp_required, only: [:create] - def show; end + def show + @confirmation = Form::TwoFactorConfirmation.new + end def create current_user.otp_secret = User.generate_otp_secret(32) @@ -16,13 +18,23 @@ module Settings end def destroy - current_user.otp_required_for_login = false - current_user.save! - redirect_to settings_two_factor_authentication_path + if current_user.validate_and_consume_otp!(confirmation_params[:code]) + current_user.otp_required_for_login = false + current_user.save! + redirect_to settings_two_factor_authentication_path + else + flash.now[:alert] = I18n.t('two_factor_authentication.wrong_code') + @confirmation = Form::TwoFactorConfirmation.new + render :show + end end private + def confirmation_params + params.require(:form_two_factor_confirmation).permit(:code) + end + def verify_otp_required redirect_to settings_two_factor_authentication_path if current_user.otp_required_for_login? end diff --git a/app/javascript/styles/admin.scss b/app/javascript/styles/admin.scss index c2bfc10a0..3bc713566 100644 --- a/app/javascript/styles/admin.scss +++ b/app/javascript/styles/admin.scss @@ -129,6 +129,11 @@ color: $ui-primary-color; } } + + .positive-hint { + color: $valid-value-color; + font-weight: 500; + } } .simple_form { diff --git a/app/javascript/styles/forms.scss b/app/javascript/styles/forms.scss index 059c4a7d8..7a181f36b 100644 --- a/app/javascript/styles/forms.scss +++ b/app/javascript/styles/forms.scss @@ -358,7 +358,6 @@ code { } .user_filtered_languages { - & > label { font-family: inherit; font-size: 16px; diff --git a/app/javascript/styles/lists.scss b/app/javascript/styles/lists.scss index 47805663f..6019cd800 100644 --- a/app/javascript/styles/lists.scss +++ b/app/javascript/styles/lists.scss @@ -10,7 +10,6 @@ .recovery-codes { list-style: none; margin: 0 auto; - text-align: center; li { font-size: 125%; diff --git a/app/views/settings/two_factor_authentication/recovery_codes/index.html.haml b/app/views/settings/two_factor_authentication/recovery_codes/index.html.haml index 7d409826e..d47ee840e 100644 --- a/app/views/settings/two_factor_authentication/recovery_codes/index.html.haml +++ b/app/views/settings/two_factor_authentication/recovery_codes/index.html.haml @@ -1,7 +1,7 @@ - content_for :page_title do = t('settings.two_factor_authentication') -%p.hint= t('two_factor_authentication.recovery_instructions') +%p.hint= t('two_factor_authentication.recovery_instructions_html') %ol.recovery-codes - @recovery_codes.each do |code| diff --git a/app/views/settings/two_factor_authentications/show.html.haml b/app/views/settings/two_factor_authentications/show.html.haml index 88b5bd20e..8ba42a101 100644 --- a/app/views/settings/two_factor_authentications/show.html.haml +++ b/app/views/settings/two_factor_authentications/show.html.haml @@ -1,26 +1,34 @@ - content_for :page_title do = t('settings.two_factor_authentication') -.simple_form - %p.hint - = t('two_factor_authentication.description_html') +- if current_user.otp_required_for_login + %p.positive-hint + = fa_icon 'check' + = ' ' + = t 'two_factor_authentication.enabled' - - if current_user.otp_required_for_login - = link_to t('two_factor_authentication.disable'), - settings_two_factor_authentication_path, - data: { method: :delete }, - class: 'block-button' - - else - = link_to t('two_factor_authentication.setup'), - settings_two_factor_authentication_path, - data: { method: :post }, - class: 'block-button' + %hr/ -- if current_user.otp_required_for_login - .simple_form - %p.hint - = t('two_factor_authentication.lost_recovery_codes') + = simple_form_for @confirmation, url: settings_two_factor_authentication_path, method: :delete do |f| + = f.input :code, hint: t('two_factor_authentication.code_hint'), placeholder: t('simple_form.labels.defaults.otp_attempt') + + .actions + = f.button :button, t('two_factor_authentication.disable'), type: :submit + + %hr/ + + %h6= t('two_factor_authentication.recovery_codes') + %p.muted-hint + = t('two_factor_authentication.lost_recovery_codes') = link_to t('two_factor_authentication.generate_recovery_codes'), settings_two_factor_authentication_recovery_codes_path, + data: { method: :post } + +- else + .simple_form + %p.hint= t('two_factor_authentication.description_html') + + = link_to t('two_factor_authentication.setup'), + settings_two_factor_authentication_path, data: { method: :post }, class: 'block-button' diff --git a/config/locales/ca.yml b/config/locales/ca.yml index 24fc5690d..2fbc63ef9 100644 --- a/config/locales/ca.yml +++ b/config/locales/ca.yml @@ -360,7 +360,7 @@ ca: lost_recovery_codes: Els codis de recuperació et permeten recuperar l'accés al teu compte si perds el telèfon. Si has perdut els teus codis de recuperació els pots regenerar aquí. Els codis de recuperació anteriors seran anul·lats. manual_instructions: 'Si no pots escanejar el codi QR code i necessites introduir-lo manualment, aquí tens el secret en text plà:' recovery_codes_regenerated: Codis de recuperació regenerats amb èxit - recovery_instructions: Si alguna vegada perds l'accéss al telèfon pots utilitzar un dels codis de recuperació a continuació per recuperar l'accés al teu compte. Cal mantenir els codis de recuperació en lloc segur, per exemple imprimint-los i guardar-los amb altres documents importants. + recovery_instructions_html: Si alguna vegada perds l'accéss al telèfon pots utilitzar un dels codis de recuperació a continuació per recuperar l'accés al teu compte. Cal mantenir els codis de recuperació en lloc segur, per exemple imprimint-los i guardar-los amb altres documents importants. setup: Establir wrong_code: El codi introduït es invalid! Es correcta la hora del servidor i del dispositiu? users: diff --git a/config/locales/de.yml b/config/locales/de.yml index 72d60d2a0..f2841d0b7 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -304,7 +304,7 @@ de: lost_recovery_codes: Wiederherstellungscodes erlauben dir, wieder den Zugang zu deinem Konto zu erlangen, falls du dein Telefon verlierst. Wenn du deine Wiederherstellungscodes verloren hast, kannst du sie hier regenerieren. Deine alten Wiederherstellungscodes werden damit ungültig gemacht. manual_instructions: 'Wenn du den QR-Code nicht einlesen kannst und ihn manuell eingeben musst, ist hier das Klartext-Geheimnis:' recovery_codes_regenerated: Wiederherstellungscodes erfolgreich regeneriert - recovery_instructions: Wenn du jemals den Zugang zu deinem Telefon verlierst, kannst du einen der Wiederherstellungscodes unten benutzen, um wieder auf dein Konto zugreifen zu können. Bewahre die Wiederherstellungscodes sicher auf, indem du sie beispielsweise ausdruckst und sie zusammen mit anderen wichtigen Dokumenten lagerst. + recovery_instructions_html: Wenn du jemals den Zugang zu deinem Telefon verlierst, kannst du einen der Wiederherstellungscodes unten benutzen, um wieder auf dein Konto zugreifen zu können. Bewahre die Wiederherstellungscodes sicher auf, indem du sie beispielsweise ausdruckst und sie zusammen mit anderen wichtigen Dokumenten lagerst. setup: Einrichten wrong_code: Der eingegebene Code war ungültig! Sind die Server- und die Gerätezeit korrekt? users: diff --git a/config/locales/en.yml b/config/locales/en.yml index 7238949dc..9daaf53ec 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -391,13 +391,17 @@ en: description_html: If you enable two-factor authentication, logging in will require you to be in possession of your phone, which will generate tokens for you to enter. disable: Disable enable: Enable + enabled: Two-factor authentication is enabled enabled_success: Two-factor authentication successfully enabled - generate_recovery_codes: Generate Recovery Codes + generate_recovery_codes: Generate recovery codes instructions_html: "Scan this QR code into Google Authenticator or a similiar TOTP app on your phone. From now on, that app will generate tokens that you will have to enter when logging in." lost_recovery_codes: Recovery codes allow you to regain access to your account if you lose your phone. If you've lost your recovery codes, you can regenerate them here. Your old recovery codes will be invalidated. manual_instructions: 'If you can''t scan the QR code and need to enter it manually, here is the plain-text secret:' + recovery_codes: Backup recovery codes recovery_codes_regenerated: Recovery codes successfully regenerated - recovery_instructions: If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe. (For example, you may print them and store them with other important documents.) + recovery_instructions_html: + If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe. + For example, you may print them and store them with other important documents. setup: Set up wrong_code: The entered code was invalid! Are server time and device time correct? users: diff --git a/config/locales/fa.yml b/config/locales/fa.yml index a65de2365..515443608 100644 --- a/config/locales/fa.yml +++ b/config/locales/fa.yml @@ -334,7 +334,7 @@ fa: lost_recovery_codes: با کدهای بازیابی می‌توانید اگر تلفن خود را گم کردید به حساب خود دسترسی داشته باشید. اگر کدهای بازیابی خود را گم کردید، آن‌ها را این‌جا دوباره بسازید. کدهای بازیابی قبلی شما نامعتبر خواهند شد. manual_instructions: 'اگر نمی‌توانید کدها را اسکن کنید و باید آن‌ها را دستی وارد کنید، متن کد امنیتی این‌جاست:' recovery_codes_regenerated: کدهای بازیابی با موفقیت ساخته شدند - recovery_instructions: اگر تلفن خود را گم کردید، می‌توانید با یکی از کدهای بازیابی زیر کنترل حساب خود را به دست بگیرید. این کدها را در جای امنی نگه دارید، مثلاً آن‌ها را چاپ کنید و کنار سایر مدارک مهم خود قرار دهید + recovery_instructions_html: اگر تلفن خود را گم کردید، می‌توانید با یکی از کدهای بازیابی زیر کنترل حساب خود را به دست بگیرید. این کدها را در جای امنی نگه دارید، مثلاً آن‌ها را چاپ کنید و کنار سایر مدارک مهم خود قرار دهید setup: راه اندازی wrong_code: کدی که وارد کردید نامعتبر بود! آیا ساعت سرور و ساعت دستگاه شما درست تنظیم شده‌اند؟ users: diff --git a/config/locales/fr.yml b/config/locales/fr.yml index 7f348986e..0c3f3b1d5 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -300,7 +300,7 @@ fr: lost_recovery_codes: Les codes de récupération vous permettent de retrouver les accès à votre comptre si vous perdez votre téléphone. Si vous perdez vos codes de récupération, vous pouvez les générer à nouveau ici. Vos anciens codes de récupération seront invalidés. manual_instructions: 'Si vous ne pouvez pas scanner ce QR code et devez l''entrer manuellement, voici le secret en clair :' recovery_codes_regenerated: Codes de récupération régénérés avec succès - recovery_instructions: Si vous perdez l'accès à votre téléphone, vous pouvez utiliser un des codes de récupération ci-dessous pour récupérer l'accès à votre compte. Conservez les codes de récupération en toute sécurité, par exemple, en les imprimant et en les stockant avec vos autres documents importants. + recovery_instructions_html: Si vous perdez l'accès à votre téléphone, vous pouvez utiliser un des codes de récupération ci-dessous pour récupérer l'accès à votre compte. Conservez les codes de récupération en toute sécurité, par exemple, en les imprimant et en les stockant avec vos autres documents importants. setup: Installer wrong_code: Les codes entrés sont incorrects ! L'heure du serveur et celle de votre appareil sont-elles correctes ? users: diff --git a/config/locales/he.yml b/config/locales/he.yml index 7e3b40b1c..ec7d972ec 100644 --- a/config/locales/he.yml +++ b/config/locales/he.yml @@ -342,7 +342,7 @@ he: lost_recovery_codes: קודי האחזור מאפשרים אחזור גישה לחשבון במידה ומכשירך אבד. במידה וקודי האחזור אבדו, ניתן לייצרם מחדש כאן. תוקף קודי האחזור הישנים יפוג. manual_instructions: 'במידה ולא ניתן לסרוק את קוד ה-QR אלא יש צורך להקליד אותו ידנית, להלן סוד כמוס בלתי מוצפן:' recovery_codes_regenerated: קודי האחזור יוצרו בהצלחה - recovery_instructions: במידה והגישה למכשירך תאבד, ניתן לייצר קודי אחזור למטה על מנת לאחזר גישה לחשבונך בכל עת. נא לשמור על קודי הגישה במקום בטוח )לדוגמא על ידי הדפסתם ושמירתם עם מסמכים חשובים אחרים, או שימוש בתוכנה ייעודית לניהול סיסמאות וסודות( + recovery_instructions_html: במידה והגישה למכשירך תאבד, ניתן לייצר קודי אחזור למטה על מנת לאחזר גישה לחשבונך בכל עת. נא לשמור על קודי הגישה במקום בטוח )לדוגמא על ידי הדפסתם ושמירתם עם מסמכים חשובים אחרים, או שימוש בתוכנה ייעודית לניהול סיסמאות וסודות( setup: הכנה wrong_code: הקוד שהוזן שגוי! האם הזמן בשרת והזמן במכשירך נכונים? users: diff --git a/config/locales/id.yml b/config/locales/id.yml index 300612b31..fc4ffd046 100644 --- a/config/locales/id.yml +++ b/config/locales/id.yml @@ -331,7 +331,7 @@ id: lost_recovery_codes: Kode pemulihan bisa anda gunakan untuk mendapatkan kembali akses pada akun anda jika anda kehilangan handphone anda. Jika anda kehilangan kode pemulihan, anda bisa membuatnya ulang disini. Kode pemulihan anda yang lama tidak akan bisa digunakan lagi. manual_instructions: 'Jika anda tidak bisa memindai kode QR dan harus memasukkannya secara manual, ini dia kode yang harus dimasukkan:' recovery_codes_regenerated: Kode Pemulihan berhasil dibuat ulang - recovery_instructions: Jika anda kehilangan akses pada handphone anda, anda bisa menggunakan kode pemulihan dibawah ini untuk mendapatkan kembali akses pada akun anda. Simpan kode pemulihan anda baik-baik, misalnya dengan mencetaknya atau menyimpannya bersama dokumen penting lainnya. + recovery_instructions_html: Jika anda kehilangan akses pada handphone anda, anda bisa menggunakan kode pemulihan dibawah ini untuk mendapatkan kembali akses pada akun anda. Simpan kode pemulihan anda baik-baik, misalnya dengan mencetaknya atau menyimpannya bersama dokumen penting lainnya. setup: Persiapan wrong_code: Kode yang dimasukkan tidak cocok! Apa waktu server dan waktu di handphone sudah cocok? users: diff --git a/config/locales/io.yml b/config/locales/io.yml index def5b9524..db430b0fe 100644 --- a/config/locales/io.yml +++ b/config/locales/io.yml @@ -303,7 +303,7 @@ io: lost_recovery_codes: Recovery codes allow you to regain access to your account if you lose your phone. If you've lost your recovery codes, you can regenerate them here. Your old recovery codes will be invalidated. manual_instructions: 'If you can''t scan the QR code and need to enter it manually, here is the plain-text secret:' recovery_codes_regenerated: Recovery codes successfully regenerated - recovery_instructions: If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe, for example by printing them and storing them with other important documents. + recovery_instructions_html: If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe, for example by printing them and storing them with other important documents. setup: Set up wrong_code: The entered code was invalid! Are server time and device time correct? users: diff --git a/config/locales/ja.yml b/config/locales/ja.yml index 94f02e940..80169339d 100644 --- a/config/locales/ja.yml +++ b/config/locales/ja.yml @@ -360,7 +360,7 @@ ja: lost_recovery_codes: リカバリーコードを使用すると携帯電話を紛失した場合でもアカウントにアクセスできるようになります。 リカバリーコードを紛失した場合もここで再生成することができますが、古いリカバリーコードは無効になります。 manual_instructions: 'QRコードがスキャンできず、手動での登録を希望の場合はこのシークレットコードを利用してください。:' recovery_codes_regenerated: リカバリーコードが再生成されました。 - recovery_instructions: 携帯電話を紛失した場合、以下の内どれかのリカバリーコードを使用してアカウントへアクセスすることができます。 リカバリーコードは印刷して安全に保管してください。 + recovery_instructions_html: 携帯電話を紛失した場合、以下の内どれかのリカバリーコードを使用してアカウントへアクセスすることができます。 リカバリーコードは印刷して安全に保管してください。 setup: 初期設定 wrong_code: コードが間違っています。サーバー上の時間とデバイス上の時間が一致していることを確認してください。 users: diff --git a/config/locales/nl.yml b/config/locales/nl.yml index 15d963808..d9b02e09c 100644 --- a/config/locales/nl.yml +++ b/config/locales/nl.yml @@ -228,7 +228,7 @@ nl: lost_recovery_codes: Met herstelcodes kun je toegang tot jouw account krijgen wanneer je jouw telefoon bent kwijtgeraakt. Wanneer je jouw herstelcodes bent kwijtgeraakt, kan je ze hier opnieuw genereren. Jouw oude herstelcodes zijn daarna ongeldig. manual_instructions: 'Hieronder vind je de geheime code in platte tekst. Voor het geval je de QR-code niet kunt scannen en het handmatig moet invoeren.' recovery_codes_regenerated: Opnieuw genereren herstelcodes geslaagd - recovery_instructions: Wanneer je ooit de toegang verliest tot jouw telefoon, kan je met behulp van een van de herstelcodes hieronder opnieuw toegang krijgen tot jouw account. Zorg ervoor dat je de herstelcodes op een veilige plek bewaard. (Je kunt ze bijvoorbeeld printen en ze samen met andere belangrijke documenten bewaren.) + recovery_instructions_html: Wanneer je ooit de toegang verliest tot jouw telefoon, kan je met behulp van een van de herstelcodes hieronder opnieuw toegang krijgen tot jouw account. Zorg ervoor dat je de herstelcodes op een veilige plek bewaard. (Je kunt ze bijvoorbeeld printen en ze samen met andere belangrijke documenten bewaren.) setup: Instellen wrong_code: De ingevoerde code is ongeldig! Klopt de systeemtijd van de server en die van jouw apparaat? users: diff --git a/config/locales/no.yml b/config/locales/no.yml index 1cd6620b6..f71c08c6a 100644 --- a/config/locales/no.yml +++ b/config/locales/no.yml @@ -335,7 +335,7 @@ lost_recovery_codes: Gjenopprettingskoder lar deg gjenoppnå tilgang til din konto hvis du mister din telefon. Hvis du har mistet gjenopprettingskodene, kan du regenerere dem her. Dine gamle gjenopprettingskoder vil bli ugyldige. manual_instructions: 'Hvis du ikke får scannet QR-koden må du skrive inn følgende kode manuelt:' recovery_codes_regenerated: Generering av gjenopprettingskoder vellykket - recovery_instructions: Hvis du skulle miste tilgang til telefonen din, kan du bruke en av gjenopprettingskodene nedenfor til å gjenopprette tilgang til din konto. Oppbevar gjenopprettingskodene sikkert, for eksempel ved å skrive dem ut og lagre dem sammen med andre viktige dokumenter. + recovery_instructions_html: Hvis du skulle miste tilgang til telefonen din, kan du bruke en av gjenopprettingskodene nedenfor til å gjenopprette tilgang til din konto. Oppbevar gjenopprettingskodene sikkert, for eksempel ved å skrive dem ut og lagre dem sammen med andre viktige dokumenter. setup: Sett opp wrong_code: Den angitte koden var ugyldig! Stemmer instansens tid overalt med enhetens tid? users: diff --git a/config/locales/oc.yml b/config/locales/oc.yml index 3770c0671..c882b43a1 100644 --- a/config/locales/oc.yml +++ b/config/locales/oc.yml @@ -220,7 +220,7 @@ oc: - dv - ds abbr_month_names: - - + - - gen - feb - mar @@ -246,7 +246,7 @@ oc: long: Lo %B %d de %Y short: "%b %d" month_names: - - + - - de genièr - de febrièr - de març @@ -411,7 +411,7 @@ oc: lost_recovery_codes: Los còdi de recuperacion vos permeton d’accedir a vòstre compte se perdètz vòstre mobil. S’avètz perdut vòstres còdis de recuperacion los podètz tornar generar aquí. Los ancians còdis seràn pas mai valides. manual_instructions: 'Se podètz pas numerizar lo còdi QR e que vos cal picar lo còdi a la man, vaquí lo còdi en clar :' recovery_codes_regenerated: Los còdis de recuperacion son ben estats tornats generar - recovery_instructions: Se vos arriba de perdre vòstre mobil, podètz utilizar un dels còdis de recuperacion cai-jos per poder tornar accedir a vòstre compte. Gardatz los còdis en seguretat, per exemple, imprimissètz los e gardatz los amb vòstres documents importants. + recovery_instructions_html: Se vos arriba de perdre vòstre mobil, podètz utilizar un dels còdis de recuperacion cai-jos per poder tornar accedir a vòstre compte. Gardatz los còdis en seguretat, per exemple, imprimissètz los e gardatz los amb vòstres documents importants. setup: Paramètres wrong_code: Lo còdi picat es invalid ! L’ora es la bona sul servidor e lo mobil ? users: diff --git a/config/locales/pl.yml b/config/locales/pl.yml index 7376c3e2b..97d20aa41 100644 --- a/config/locales/pl.yml +++ b/config/locales/pl.yml @@ -364,7 +364,7 @@ pl: lost_recovery_codes: Kody zapasowe pozwolą uzyskać dostęp do portalu, jeżeli utracisz dostęp do telefonu. Jeżeli utracisz dostęp do nich, możesz wygenerować je ponownie tutaj. Poprzednie zostaną unieważnione. manual_instructions: 'Jeżeli nie możesz zeskanować kodu QR, musisz wprowadzić ten kod ręcznie:' recovery_codes_regenerated: Pomyślnie wygenerowano ponownie kody zapasowe - recovery_instructions: Jeżeli kiedykolwiek utracisz dostęp do telefonu, możesz wykorzystać jeden z kodów zapasowych, aby odzyskać dostęp do konta. Trzymaj je w bezpiecznym miejscu. (Na przykład, wydrukuj je i przechowuj z ważnymu dokumentami.) + recovery_instructions_html: Jeżeli kiedykolwiek utracisz dostęp do telefonu, możesz wykorzystać jeden z kodów zapasowych, aby odzyskać dostęp do konta. Trzymaj je w bezpiecznym miejscu. (Na przykład, wydrukuj je i przechowuj z ważnymu dokumentami.) setup: Skonfiguruj wrong_code: Wprowadzony kod jest niepoprawny! Czy czas serwera i urządzenia jest poprawny? users: diff --git a/config/locales/pt-BR.yml b/config/locales/pt-BR.yml index b6f5497bd..973a8d401 100644 --- a/config/locales/pt-BR.yml +++ b/config/locales/pt-BR.yml @@ -333,7 +333,7 @@ pt-BR: lost_recovery_codes: Códigos de recuperação permite que você recupere o acesso a sua conta se você perder seu telefone. Se você perder os códigos de recuperação, você pode regera-los aqui. Seus códigos antigos serão invalidados. manual_instructions: 'Se você não puder scanear o código QR e precisa digita-los manualmente, aqui está o segredo em texto.:' recovery_codes_regenerated: Códigos de recuperação foram gerados com sucesso - recovery_instructions: Se algum dia você perder o acesso ao seu telefone, você pode usar um dos códigos de abaixo para recupera o acesso a sua conta. Guarde os códigos de acesso em local seguro, por exemplo imprimindo ou guardados com documentos importantes. + recovery_instructions_html: Se algum dia você perder o acesso ao seu telefone, você pode usar um dos códigos de abaixo para recupera o acesso a sua conta. Guarde os códigos de acesso em local seguro, por exemplo imprimindo ou guardados com documentos importantes. setup: Configurar wrong_code: O código digitado é inválido! Os relógios do servidor e do dispositivo estão corretos? users: diff --git a/config/locales/ru.yml b/config/locales/ru.yml index c16ab6869..9cf067d88 100644 --- a/config/locales/ru.yml +++ b/config/locales/ru.yml @@ -332,7 +332,7 @@ ru: lost_recovery_codes: Коды восстановления позволяют вернуть доступ к аккаунту в случае утери телефона. Если Вы потеряли Ваши коды восстановления, вы можете заново сгенерировать их здесь. Ваши старые коды восстановления будут аннулированы. manual_instructions: 'Если Вы не можете отсканировать QR-код и хотите ввести его вручную, секрет представлен здесь открытым текстом:' recovery_codes_regenerated: Коды восстановления успешно сгенерированы - recovery_instructions: В случае утери доступа к Вашему телефону Вы можете использовать один из кодов восстановления, указанных ниже, чтобы вернуть доступ к аккаунту. Держите коды восстановления в безопасности, например, распечатав их и храня с другими важными документами. + recovery_instructions_html: В случае утери доступа к Вашему телефону Вы можете использовать один из кодов восстановления, указанных ниже, чтобы вернуть доступ к аккаунту. Держите коды восстановления в безопасности, например, распечатав их и храня с другими важными документами. setup: Настроить wrong_code: Введенный код неверен! Правильно ли установлены серверное время и время устройства? users: diff --git a/config/locales/th.yml b/config/locales/th.yml index 6ef4b6789..322e5e74b 100644 --- a/config/locales/th.yml +++ b/config/locales/th.yml @@ -335,7 +335,7 @@ th: lost_recovery_codes: Recovery codes allow you to regain access to your account if you lose your phone. If you've lost your recovery codes, you can regenerate them here. Your old recovery codes will be invalidated. manual_instructions: 'If you can''t scan the QR code and need to enter it manually, here is the plain-text secret:' recovery_codes_regenerated: Recovery codes successfully regenerated - recovery_instructions: If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe, for example by printing them and storing them with other important documents. + recovery_instructions_html: If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe, for example by printing them and storing them with other important documents. setup: ตั้งค่า wrong_code: รหัสที่กรอกไม่ถูกต้อง! Are server time and device time correct? users: diff --git a/config/locales/tr.yml b/config/locales/tr.yml index a4c870b64..0e33e2efe 100644 --- a/config/locales/tr.yml +++ b/config/locales/tr.yml @@ -333,7 +333,7 @@ tr: lost_recovery_codes: Kurtarma kodları telefonunuzu kaybettiğiniz durumlarda hesabınıza erişim yapabilmenize olanak tanır. Eğer kurtarma kodlarınızı kaybettiyseniz burada tekrar oluşturabilirsiniz. Eski kurtarma kodlarınız geçersiz hale gelecektir. manual_instructions: 'Eğer QR kodunu taratamıyorsanız ve elle giriş yapmanız gerekiyorsa buradaki gizli düz metni girebilirsiniz:' recovery_codes_regenerated: Kurtarma kodları başarıyla oluşturuldu - recovery_instructions: 'Eğer telefonunuza erişiminizi kaybederseniz, aşağıdaki kurtarma kodlarından birini kullanarak hesabınıza giriş yapabilirsiniz. Kurtarma kodlarınızı güvenli halde tutunuz. Örneğin: kodların çıktısını alıp diğer önemli belgeleriniz ile birlikte saklayabilirsiniz.' + recovery_instructions_html: 'Eğer telefonunuza erişiminizi kaybederseniz, aşağıdaki kurtarma kodlarından birini kullanarak hesabınıza giriş yapabilirsiniz. Kurtarma kodlarınızı güvenli halde tutunuz. Örneğin: kodların çıktısını alıp diğer önemli belgeleriniz ile birlikte saklayabilirsiniz.' setup: Kuruluma başla wrong_code: Girdiğiniz kod geçersiz! Telefonunuzun saati geri/ileri kalmış olabilir. users: diff --git a/config/locales/uk.yml b/config/locales/uk.yml index c1ec61cda..1327c1a7b 100644 --- a/config/locales/uk.yml +++ b/config/locales/uk.yml @@ -319,7 +319,7 @@ uk: lost_recovery_codes: Коди відновлення дозволяють повернути доступ до акаунту у випадку втрати телефону. Якщо Ви втратили Ваші коди відновлення, Ви можете знову згенерувати їх тут. Ваші старі коди відновлення будуть анульовані. manual_instructions: 'Якщо Ви не можете відсканувати QR-код та хочете ввести його вручну, секрет представлений тут відкритим текстом:' recovery_codes_regenerated: Коди відновлення успішно згенеровані - recovery_instructions: У випадку втрати доступу до Вашого телефона Ви можете використати один з кодів відновлення, вказаних нижче, щоб повернути доступ до акаунту. Тримайте коди відновлення у безпеці, наприклад, роздрукувавши їх та тримаючи їх з іншими важливими документами. + recovery_instructions_html: У випадку втрати доступу до Вашого телефона Ви можете використати один з кодів відновлення, вказаних нижче, щоб повернути доступ до акаунту. Тримайте коди відновлення у безпеці, наприклад, роздрукувавши їх та тримаючи їх з іншими важливими документами. setup: Налаштувати wrong_code: Введений код неправильний! Чи правильно встановлені серверний час та час пристрою? users: diff --git a/config/locales/zh-CN.yml b/config/locales/zh-CN.yml index 9bf338ea4..6c8e9fc6d 100644 --- a/config/locales/zh-CN.yml +++ b/config/locales/zh-CN.yml @@ -339,7 +339,7 @@ zh-CN: lost_recovery_codes: 如果你丢了手机,你可以用恢复代码重新访问你的账户。如果你丢了恢复代码,也可以在这里重新生成一个,不过以前的恢复代码就失效了。(废话) manual_instructions: 如果你无法扫描 QR 二维码,请手动输入这个文本密码︰ recovery_codes_regenerated: 已成功重新生成恢复代码 - recovery_instructions: 如果你的手机无法使用,你可以使用下面的任何恢复代码来恢复你的账号。请保管好你的恢复代码以防泄漏(例如你可以打印好它们并和重要文档一起保存)。 + recovery_instructions_html: 如果你的手机无法使用,你可以使用下面的任何恢复代码来恢复你的账号。请保管好你的恢复代码以防泄漏(例如你可以打印好它们并和重要文档一起保存)。 setup: 设置 wrong_code: 你输入的认证码并不正确!可能服务器时间和你手机不一致,请检查你手机的时钟,或与本站管理员联系。 users: diff --git a/config/locales/zh-HK.yml b/config/locales/zh-HK.yml index 9a110f7da..4d8262c5b 100644 --- a/config/locales/zh-HK.yml +++ b/config/locales/zh-HK.yml @@ -334,7 +334,7 @@ zh-HK: lost_recovery_codes: 讓你可以在遺失電話時,使用備用驗證碼登入。如果你遺失了備用驗證碼,可以在這裏產生一批新的,舊有的備用驗證碼將會失效。 manual_instructions: 如果你無法掃描 QR 圖形碼,請手動輸入這個文字密碼︰ recovery_codes_regenerated: 成功產生新的備用驗證碼 - recovery_instructions: 如果你遺失了安裝認證器的裝置(如︰你的電話),你可以使用備用驗證碼進行登入。請確保將備用驗證碼收藏穩當,(如列印出來,和你其他重要文件一起存放) + recovery_instructions_html: 如果你遺失了安裝認證器的裝置(如︰你的電話),你可以使用備用驗證碼進行登入。請確保將備用驗證碼收藏穩當,(如列印出來,和你其他重要文件一起存放) setup: 設定 wrong_code: 你輸入的認證碼並不正確!可能伺服器時間和你手機不一致,請檢查你手機的時鐘,或與本站管理員聯絡。 users: diff --git a/spec/controllers/settings/two_factor_authentications_controller_spec.rb b/spec/controllers/settings/two_factor_authentications_controller_spec.rb index 4d1a01fcf..6c49f6f0d 100644 --- a/spec/controllers/settings/two_factor_authentications_controller_spec.rb +++ b/spec/controllers/settings/two_factor_authentications_controller_spec.rb @@ -79,13 +79,41 @@ describe Settings::TwoFactorAuthenticationsController do user.update(otp_required_for_login: true) end - it 'turns off otp requirement if signed in' do - sign_in user, scope: :user - post :destroy + context 'when signed in' do + before do + sign_in user, scope: :user + end - expect(response).to redirect_to(settings_two_factor_authentication_path) - user.reload - expect(user.otp_required_for_login).to eq(false) + it 'turns off otp requirement with correct code' do + expect_any_instance_of(User).to receive(:validate_and_consume_otp!) do |value, arg| + expect(value).to eq user + expect(arg).to eq '123456' + true + end + + post :destroy, params: { form_two_factor_confirmation: { code: '123456' } } + + expect(response).to redirect_to(settings_two_factor_authentication_path) + user.reload + expect(user.otp_required_for_login).to eq(false) + end + + it 'does not turn off otp if code is incorrect' do + expect_any_instance_of(User).to receive(:validate_and_consume_otp!) do |value, arg| + expect(value).to eq user + expect(arg).to eq '057772' + false + end + + post :destroy, params: { form_two_factor_confirmation: { code: '057772' } } + + user.reload + expect(user.otp_required_for_login).to eq(true) + end + + it 'raises ActionController::ParameterMissing if code is missing' do + expect { post :destroy }.to raise_error(ActionController::ParameterMissing) + end end it 'redirects if not signed in' do -- cgit From f53ed108b0c6218eef118bbd0b77078d36c46a96 Mon Sep 17 00:00:00 2001 From: Alda Marteau-Hardi Date: Mon, 26 Jun 2017 13:04:36 +0200 Subject: Translate pin/unpin and fix some inconsistencies in gender neutral strings (#3952) --- app/javascript/mastodon/locales/fr.json | 6 +++--- config/locales/fr.yml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'config') diff --git a/app/javascript/mastodon/locales/fr.json b/app/javascript/mastodon/locales/fr.json index 52d6b0f87..1a69235c8 100644 --- a/app/javascript/mastodon/locales/fr.json +++ b/app/javascript/mastodon/locales/fr.json @@ -27,8 +27,8 @@ "column.notifications": "Notifications", "column.public": "Fil public global", "column_back_button.label": "Retour", - "column_header.pin": "Pin", - "column_header.unpin": "Unpin", + "column_header.pin": "Épingler", + "column_header.unpin": "Retirer", "column_subheading.navigation": "Navigation", "column_subheading.settings": "Paramètres", "compose_form.lock_disclaimer": "Votre compte n'est pas {locked}. Tout le monde peut vous suivre et voir vos pouets restreints.", @@ -101,7 +101,7 @@ "notifications.clear_confirmation": "Voulez-vous vraiment supprimer toutes vos notifications ?", "notifications.column_settings.alert": "Notifications locales", "notifications.column_settings.favourite": "Favoris :", - "notifications.column_settings.follow": "Nouveaux abonné⋅e⋅s :", + "notifications.column_settings.follow": "Nouveaux⋅elles abonn⋅é⋅s :", "notifications.column_settings.mention": "Mentions :", "notifications.column_settings.reblog": "Partages :", "notifications.column_settings.show": "Afficher dans la colonne", diff --git a/config/locales/fr.yml b/config/locales/fr.yml index 0c3f3b1d5..dfe5ff990 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -238,7 +238,7 @@ fr: mention: "%{name} vous a mentionné⋅e" new_followers_summary: one: Vous avez un⋅e nouvel⋅le abonné⋅e ! Youpi ! - other: Vous avez %{count} nouveaux abonné⋅es ! Incroyable ! + other: Vous avez %{count} nouveaux⋅elles abonné⋅e⋅s ! Incroyable ! subject: one: "Une nouvelle notification depuis votre dernière visite \U0001F418" other: "%{count} nouvelles notifications depuis votre dernière visite \U0001F418" -- cgit From ae2b722f5510cc5ab54cd5e6419136f1a63892df Mon Sep 17 00:00:00 2001 From: m4sk1n Date: Mon, 26 Jun 2017 17:10:54 +0200 Subject: i18n: Warning to look into the spam folder (pl) (#3955) --- config/locales/devise.pl.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'config') diff --git a/config/locales/devise.pl.yml b/config/locales/devise.pl.yml index d4ee1b6ae..792e0d81e 100644 --- a/config/locales/devise.pl.yml +++ b/config/locales/devise.pl.yml @@ -3,8 +3,8 @@ pl: devise: confirmations: confirmed: Twój adres e-mail został poprawnie zweryfikowany. - send_instructions: W ciągu kilku minut otrzymasz wiadomosć e-mail z instrukcją jak potwierdzić Twój adres e-mail. - send_paranoid_instructions: Jeśli Twój adres e-mail już istnieje w naszej bazie danych, w ciągu kilku minut otrzymasz wiadomość e-mail z instrukcją jak potwierdzić Twój adres e-mail. + send_instructions: W ciągu kilku minut otrzymasz wiadomosć e-mail z instrukcją jak potwierdzić Twój adres e-mail. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. + send_paranoid_instructions: Jeśli Twój adres e-mail już istnieje w naszej bazie danych, w ciągu kilku minut otrzymasz wiadomość e-mail z instrukcją jak potwierdzić Twój adres e-mail. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. failure: already_authenticated: Jesteś już zalogowany/zalogowana. inactive: Twoje konto nie zostało jeszcze aktywowane. @@ -29,8 +29,8 @@ pl: success: Uwierzytelnienie przez %{kind} powiodło się. passwords: no_token: Dostęp do tej strony możliwy jest wyłącznie za pomocą odnośnika z e-maila z instrukcjami ustawienia nowego hasła. Jeśli skorzystałeś/aś z takiego odnośnika, upewnij się, że został wykorzystany/skopiowany cały odnośnik. - send_instructions: W ciągu kilku minut otrzymasz wiadomość e-mail z instrukcją ustawienia nowego hasła. - send_paranoid_instructions: Jeśli Twój adres e-mail już istnieje w naszej bazie danych, w ciągu kilku minut otrzymasz wiadomość e-mail zawierającą odnośnik pozwalający na ustawienie nowego hasła. + send_instructions: W ciągu kilku minut otrzymasz wiadomość e-mail z instrukcją ustawienia nowego hasła. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. + send_paranoid_instructions: Jeśli Twój adres e-mail już istnieje w naszej bazie danych, w ciągu kilku minut otrzymasz wiadomość e-mail zawierającą odnośnik pozwalający na ustawienie nowego hasła. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. updated: Twoje hasło zostało zmienione. Jesteś zalogowany/a. updated_not_active: Twoje hasło zostało zmienione. registrations: @@ -38,16 +38,16 @@ pl: signed_up: Twoje konto zostało utworzone. Witamy! signed_up_but_inactive: Twoje konto zostało utworzone. Nie mogliśmy Cię jednak zalogować, ponieważ konto nie zostało jeszcze aktywowane. signed_up_but_locked: Twoje konto zostało utworzone. Nie mogliśmy Cię jednak zalogować, ponieważ konto jest zablokowane. - signed_up_but_unconfirmed: Na Twój adres e-mail została wysłana wiadomosć z odnośnikiem potwierdzającym. Kliknij w odnośnik aby aktywować konto. - update_needs_confirmation: Konto zostało zaktualizowane, musimy jednak zweryfikować Twój nowy adres e-mail. Została na niego wysłana wiadomość z odnośnikiem potwierdzającym. + signed_up_but_unconfirmed: Na Twój adres e-mail została wysłana wiadomosć z odnośnikiem potwierdzającym. Kliknij w odnośnik aby aktywować konto. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. + update_needs_confirmation: Konto zostało zaktualizowane, musimy jednak zweryfikować Twój nowy adres e-mail. Została na niego wysłana wiadomość z odnośnikiem potwierdzającym. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. updated: Konto zostało zaktualizowane. sessions: already_signed_out: Zostałeś/aś wylogowany/a. signed_in: Zostałeś/aś zalogowany/a. signed_out: Zostałeś/aś wylogowany/a. unlocks: - send_instructions: W ciągu kilku minut otrzymasz wiadomość e-mail z instrukcjami odblokowania konta. - send_paranoid_instructions: Jeśli Twoje konto istnieje, instrukcje odblokowania go otrzymasz w wiadomości e-mail w ciągu kilku minut. + send_instructions: W ciągu kilku minut otrzymasz wiadomość e-mail z instrukcjami odblokowania konta. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. + send_paranoid_instructions: Jeśli Twoje konto istnieje, instrukcje odblokowania go otrzymasz w wiadomości e-mail w ciągu kilku minut. Jeżeli nie otrzymano wiadomości, sprawdź folder ze spamem. unlocked: Twoje konto zostało odblokowane. Zaloguj się aby kontynuować. errors: messages: -- cgit From 646de92781ba9d211255a7eaf7ebca7b365612f6 Mon Sep 17 00:00:00 2001 From: m4sk1n Date: Mon, 26 Jun 2017 17:18:45 +0200 Subject: i18n: Updated Polish translation (#3956) * i18n: Updated Polish translation * Update pl.yml --- config/locales/pl.yml | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) (limited to 'config') diff --git a/config/locales/pl.yml b/config/locales/pl.yml index 97d20aa41..81eee8dc3 100644 --- a/config/locales/pl.yml +++ b/config/locales/pl.yml @@ -200,7 +200,7 @@ pl: applications: invalid_url: Ten URL jest nieprawidłowy auth: - change_password: Uwierzytelnienie + change_password: Bezpieczeństwo delete_account: Usunięcie konta delete_account_html: Jeżeli próbowałeś usunąć konto, przejdź tutaj. Otrzymasz prośbę o potwierdzenie. didnt_get_confirmation: Nie otrzymałeś instrukcji weryfikacji? @@ -323,7 +323,44 @@ pl: acct: Podaj swój adres (nazwa@domena), z którego chcesz śledzić missing_resource: Nie udało się znaleźć adresu przekierowania z Twojej domeny proceed: Śledź - prompt: 'Śledzony będzie:' + prompt: 'Zamierzasz śledzić:' + sessions: + activity: Ostatnia aktywność + browser: Przeglądarka + browsers: + alipay: Alipay + blackberry: Blackberry + chrome: Chrome + edge: Microsoft Edge + firefox: Firefox + generic: nieznana przeglądarka + ie: Internet Explorer + micro_messenger: MicroMessenger + nokia: Nokia S40 Ovi Browser + opera: Opera + phantom_js: PhantomJS + qq: QQ Browser + safari: Safari + uc_browser: UCBrowser + weibo: Weibo + current_session: Obecna sesja + description: "%{browser} na %{platform}" + explanation: Przeglądarki z aktywną sesją Twojego konta. + ip: Adres IP + platforms: + adobe_air: Adobe Air + android: Android + blackberry: Blackberry + chrome_os: ChromeOS + firefox_os: Firefox OS + ios: iOS + linux: Linux + mac: macOS + other: nieznana platforma + windows: Windows + windows_mobile: Windows Mobile + windows_phone: Windows Phone + title: Sesje settings: authorized_apps: Uwierzytelnione aplikacje back: Powrót do Mastodona @@ -358,13 +395,17 @@ pl: description_html: Jeśli włączysz uwierzytelnianie dwuetapowe, logowanie się będzie wymagało podania tokenu wyświetlonego na Twoim telefonie. disable: Wyłącz enable: Włącz + enabled: Uwierzytelnianie dwuetapowe jest włączone enabled_success: Pomyślnie aktywowano uwierzytelnianie dwuetapowe generate_recovery_codes: Generuj kody zapasowe instructions_html: "Zeskanuj ten kod QR na swoim urządzeniu za pomocą Google Authenticator, FreeOTP lub podobnej aplikacji. Od teraz będzie ona generowała kody wymagane przy logowaniu." lost_recovery_codes: Kody zapasowe pozwolą uzyskać dostęp do portalu, jeżeli utracisz dostęp do telefonu. Jeżeli utracisz dostęp do nich, możesz wygenerować je ponownie tutaj. Poprzednie zostaną unieważnione. manual_instructions: 'Jeżeli nie możesz zeskanować kodu QR, musisz wprowadzić ten kod ręcznie:' + recovery_codes: Przywróć kody zapasowe recovery_codes_regenerated: Pomyślnie wygenerowano ponownie kody zapasowe - recovery_instructions_html: Jeżeli kiedykolwiek utracisz dostęp do telefonu, możesz wykorzystać jeden z kodów zapasowych, aby odzyskać dostęp do konta. Trzymaj je w bezpiecznym miejscu. (Na przykład, wydrukuj je i przechowuj z ważnymu dokumentami.) + recovery_instructions_html: + Jeżeli kiedykolwiek utracisz dostęp do telefonu, możesz wykorzystać jeden z kodów zapasowych, aby odzyskać dostęp do konta. Trzymaj je w bezpiecznym miejscu. + Na przykład, wydrukuj je i przechowuj z ważnymu dokumentami. setup: Skonfiguruj wrong_code: Wprowadzony kod jest niepoprawny! Czy czas serwera i urządzenia jest poprawny? users: -- cgit From 42b82206322c73c4a4d7ac29ca9a781ab11e7b1a Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Tue, 27 Jun 2017 00:04:00 +0200 Subject: Fix #1624 - Send e-mail notifications to admins about new reports (#3949) --- app/controllers/api/v1/reports_controller.rb | 3 +++ app/mailers/admin_mailer.rb | 13 +++++++++++++ app/mailers/application_mailer.rb | 8 ++++++++ app/mailers/notification_mailer.rb | 8 -------- app/views/admin_mailer/new_report.text.erb | 5 +++++ config/locales/en.yml | 8 +++++--- spec/controllers/api/v1/reports_controller_spec.rb | 13 +++++++++++-- 7 files changed, 45 insertions(+), 13 deletions(-) create mode 100644 app/mailers/admin_mailer.rb create mode 100644 app/views/admin_mailer/new_report.text.erb (limited to 'config') diff --git a/app/controllers/api/v1/reports_controller.rb b/app/controllers/api/v1/reports_controller.rb index 71df76e92..8e7070d07 100644 --- a/app/controllers/api/v1/reports_controller.rb +++ b/app/controllers/api/v1/reports_controller.rb @@ -17,6 +17,9 @@ class Api::V1::ReportsController < Api::BaseController status_ids: reported_status_ids, comment: report_params[:comment] ) + + User.admins.includes(:account).each { |u| AdminMailer.new_report(u.account, @report).deliver_later } + render :show end diff --git a/app/mailers/admin_mailer.rb b/app/mailers/admin_mailer.rb new file mode 100644 index 000000000..fc19a6d40 --- /dev/null +++ b/app/mailers/admin_mailer.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +class AdminMailer < ApplicationMailer + def new_report(recipient, report) + @report = report + @me = recipient + @instance = Rails.configuration.x.local_domain + + locale_for_account(@me) do + mail to: @me.user_email, subject: I18n.t('admin_mailer.new_report.subject', instance: @instance, id: @report.id) + end + end +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb index e5dbfeeda..2e730c19b 100644 --- a/app/mailers/application_mailer.rb +++ b/app/mailers/application_mailer.rb @@ -4,4 +4,12 @@ class ApplicationMailer < ActionMailer::Base default from: ENV.fetch('SMTP_FROM_ADDRESS') { 'notifications@localhost' } layout 'mailer' helper :instance + + protected + + def locale_for_account(account) + I18n.with_locale(account.user_locale || I18n.default_locale) do + yield + end + end end diff --git a/app/mailers/notification_mailer.rb b/app/mailers/notification_mailer.rb index a944db137..12b92bf45 100644 --- a/app/mailers/notification_mailer.rb +++ b/app/mailers/notification_mailer.rb @@ -67,12 +67,4 @@ class NotificationMailer < ApplicationMailer ) end end - - private - - def locale_for_account(account) - I18n.with_locale(account.user_locale || I18n.default_locale) do - yield - end - end end diff --git a/app/views/admin_mailer/new_report.text.erb b/app/views/admin_mailer/new_report.text.erb new file mode 100644 index 000000000..6fa744bc3 --- /dev/null +++ b/app/views/admin_mailer/new_report.text.erb @@ -0,0 +1,5 @@ +<%= display_name(@me) %>, + +<%= raw t('admin_mailer.new_report.body', target: @report.target_account.acct, reporter: @report.account.acct) %> + +<%= raw t('application_mailer.view')%> <%= admin_report_url(@report) %> diff --git a/config/locales/en.yml b/config/locales/en.yml index 9daaf53ec..944c24c60 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -193,6 +193,10 @@ en: title: PubSubHubbub topic: Topic title: Administration + admin_mailer: + new_report: + body: "%{reporter} has reported %{target}" + subject: New report for %{instance} (#%{id}) application_mailer: settings: 'Change e-mail preferences: %{link}' signature: Mastodon notifications from %{instance} @@ -399,9 +403,7 @@ en: manual_instructions: 'If you can''t scan the QR code and need to enter it manually, here is the plain-text secret:' recovery_codes: Backup recovery codes recovery_codes_regenerated: Recovery codes successfully regenerated - recovery_instructions_html: - If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe. - For example, you may print them and store them with other important documents. + recovery_instructions_html: If you ever lose access to your phone, you can use one of the recovery codes below to regain access to your account. Keep the recovery codes safe. For example, you may print them and store them with other important documents. setup: Set up wrong_code: The entered code was invalid! Are server time and device time correct? users: diff --git a/spec/controllers/api/v1/reports_controller_spec.rb b/spec/controllers/api/v1/reports_controller_spec.rb index 3df6cdfe7..471ea4e0b 100644 --- a/spec/controllers/api/v1/reports_controller_spec.rb +++ b/spec/controllers/api/v1/reports_controller_spec.rb @@ -21,12 +21,21 @@ RSpec.describe Api::V1::ReportsController, type: :controller do end describe 'POST #create' do - it 'creates a report' do - status = Fabricate(:status) + let!(:status) { Fabricate(:status) } + let!(:admin) { Fabricate(:user, admin: true) } + + before do + allow(AdminMailer).to receive(:new_report).and_return(double('email', deliver_later: nil)) post :create, params: { status_ids: [status.id], account_id: status.account.id, comment: 'reasons' } + end + it 'creates a report' do expect(status.reload.account.targeted_reports).not_to be_empty expect(response).to have_http_status(:success) end + + it 'sends e-mails to admins' do + expect(AdminMailer).to have_received(:new_report).with(admin.account, Report) + end end end -- cgit From da42bfadb58888e3a18afd66395f0f3edc2fa622 Mon Sep 17 00:00:00 2001 From: m4sk1n Date: Tue, 27 Jun 2017 22:21:35 +0200 Subject: i18n: E-mail notifications to admins about new reports (pl) (#3975) --- config/locales/pl.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'config') diff --git a/config/locales/pl.yml b/config/locales/pl.yml index 81eee8dc3..113d7f235 100644 --- a/config/locales/pl.yml +++ b/config/locales/pl.yml @@ -193,9 +193,13 @@ pl: title: PubSubHubbub topic: Temat title: Administracja + admin_mailer: + new_report: + body: "Użytkownik %{reporter} zgłosił %{target}" + subject: Nowe zgłoszenie na %{instance} (#%{id}) application_mailer: settings: 'Zmień ustawienia powiadamiania: %{link}' - signature: Powiadomienie Mastodona, wysłane przez %{instance} + signature: Powiadomienie Mastodona z instancji %{instance} view: 'Zobacz:' applications: invalid_url: Ten URL jest nieprawidłowy @@ -403,9 +407,7 @@ pl: manual_instructions: 'Jeżeli nie możesz zeskanować kodu QR, musisz wprowadzić ten kod ręcznie:' recovery_codes: Przywróć kody zapasowe recovery_codes_regenerated: Pomyślnie wygenerowano ponownie kody zapasowe - recovery_instructions_html: - Jeżeli kiedykolwiek utracisz dostęp do telefonu, możesz wykorzystać jeden z kodów zapasowych, aby odzyskać dostęp do konta. Trzymaj je w bezpiecznym miejscu. - Na przykład, wydrukuj je i przechowuj z ważnymu dokumentami. + recovery_instructions_html: Jeżeli kiedykolwiek utracisz dostęp do telefonu, możesz wykorzystać jeden z kodów zapasowych, aby odzyskać dostęp do konta. Trzymaj je w bezpiecznym miejscu. Na przykład, wydrukuj je i przechowuj z ważnymu dokumentami. setup: Skonfiguruj wrong_code: Wprowadzony kod jest niepoprawny! Czy czas serwera i urządzenia jest poprawny? users: -- cgit