├── .rspec ├── .rubocop.yml ├── .travis.yml ├── Gemfile ├── Gemfile.lock ├── LICENSE ├── Procfile ├── README.md ├── Rakefile ├── app ├── api │ ├── api.rb │ ├── helper.rb │ └── v1.rb └── models │ ├── api_key.rb │ ├── folder.rb │ ├── virtual_domain.rb │ ├── virtual_domain_alias.rb │ ├── virtual_transport.rb │ ├── virtual_user.rb │ └── virtual_user_alias.rb ├── config.ru ├── config ├── application.rb ├── boot.rb ├── database.mysql2.yml ├── database.postgresql.yml ├── database.travis.mysql2.yml ├── database.travis.postgresql.yml └── environment.rb ├── db ├── migrate │ ├── 20130502150649_create_virtual_domains.rb │ ├── 20130502151649_create_virtual_users.rb │ ├── 20130502152649_create_virtual_aliases.rb │ ├── 20130614141749_add_views.rb │ ├── 20130809200149_create_virtual_domain_aliases.rb │ ├── 20130809200249_add_domain_aliases_views.rb │ ├── 20130812172949_create_user_aliases.rb │ ├── 20130812182949_create_user_aliases_view.rb │ ├── 20130812184615_add_quota_to_virtual_users.rb │ ├── 20130813150649_create_virtual_transports.rb │ ├── 20130813181249_create_api_keys.rb │ ├── 20130826162949_add_quota_to_users_view.rb │ ├── 20150508142715_migrate_user_quota_to_mb.rb │ └── 20150519141623_add_indexes.rb └── schema.rb ├── log └── .gitkeep ├── spec ├── api │ └── v1_spec.rb └── spec_helper.rb └── vendor └── config └── postfix └── samples ├── mysql-virtual-domain-aliases.cf ├── mysql-virtual-mailbox-domains.cf ├── mysql-virtual-mailbox-maps.cf ├── mysql-virtual-transports.cf └── mysql-virtual-user-aliases.cf /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --format=progress 3 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | # Include gemspec and Rakefile 3 | Include: 4 | - config.ru 5 | - Gemfile 6 | Exclude: 7 | - vendor/**/* 8 | - db/schema.rb 9 | - db/migrate/* 10 | 11 | 12 | LineLength: 13 | Max: 135 14 | 15 | Style/FileName: 16 | Enabled: false 17 | 18 | Documentation: 19 | Enabled: false 20 | 21 | ClassLength: 22 | Max: 170 -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | cache: bundler 3 | sudo: false 4 | services: 5 | - mysql 6 | - postgresql 7 | 8 | rvm: 9 | - 2.1.8 10 | - 2.2.4 11 | - 2.3.0 12 | 13 | bundler_args: "--deployment --without development production --with mysql postgresql --jobs 3 --retry 3" 14 | 15 | before_script: 16 | - sh -c "if [ '$DB' = 'mysql2' ]; then mysql -e 'create database posty_api_test;'; fi" 17 | - sh -c "if [ '$DB' = 'mysql2' ]; then cp config/database.travis.mysql2.yml config/database.yml; fi" 18 | - sh -c "if [ '$DB' = 'postgresql' ]; then psql -c 'create database posty_api_test;' -U postgres; fi" 19 | - sh -c "if [ '$DB' = 'postgresql' ]; then cp config/database.travis.postgresql.yml config/database.yml; fi" 20 | - bundle exec rake db:migrate 21 | - bundle exec rake api_key:generate 22 | 23 | script: 24 | - bundle exec rake spec 25 | - bundle exec rubocop 26 | 27 | env: 28 | - DB=mysql2 29 | - DB=postgresql -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'http://rubygems.org' 2 | 3 | gem 'rack', '~> 1.5.2' 4 | gem 'rake', '~> 10.3.2' 5 | gem 'grape', '~> 0.7.0' 6 | gem 'activerecord', '~> 3.2.22', require: 'active_record' 7 | gem 'json' 8 | gem 'grape-swagger' 9 | gem 'rack-cors', require: 'rack/cors' 10 | gem 'schema_plus', '~> 1.5.1' 11 | 12 | group :test, :development do 13 | gem 'rspec' 14 | gem 'rack-test', require: 'rack/test' 15 | gem 'shotgun' 16 | gem 'racksh' 17 | gem 'rubocop' 18 | end 19 | 20 | group :mysql, optional: true do 21 | gem 'mysql2', '~> 0.3.16' 22 | end 23 | 24 | group :postgresql, optional: true do 25 | gem 'pg', '~> 0.18.4' 26 | gem 'activerecord-postgresql-adapter' 27 | end 28 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: http://rubygems.org/ 3 | specs: 4 | activemodel (3.2.22.1) 5 | activesupport (= 3.2.22.1) 6 | builder (~> 3.0.0) 7 | activerecord (3.2.22.1) 8 | activemodel (= 3.2.22.1) 9 | activesupport (= 3.2.22.1) 10 | arel (~> 3.0.2) 11 | tzinfo (~> 0.3.29) 12 | activerecord-postgresql-adapter (0.0.1) 13 | pg 14 | activesupport (3.2.22.1) 15 | i18n (~> 0.6, >= 0.6.4) 16 | multi_json (~> 1.0) 17 | arel (3.0.3) 18 | ast (2.2.0) 19 | axiom-types (0.1.1) 20 | descendants_tracker (~> 0.0.4) 21 | ice_nine (~> 0.11.0) 22 | thread_safe (~> 0.3, >= 0.3.1) 23 | builder (3.0.4) 24 | coercible (1.0.0) 25 | descendants_tracker (~> 0.0.1) 26 | descendants_tracker (0.0.4) 27 | thread_safe (~> 0.3, >= 0.3.1) 28 | diff-lcs (1.2.5) 29 | equalizer (0.0.11) 30 | grape (0.7.0) 31 | activesupport 32 | builder 33 | hashie (>= 1.2.0) 34 | multi_json (>= 1.3.2) 35 | multi_xml (>= 0.5.2) 36 | rack (>= 1.3.0) 37 | rack-accept 38 | rack-mount 39 | virtus (>= 1.0.0) 40 | grape-entity (0.5.0) 41 | activesupport 42 | multi_json (>= 1.3.2) 43 | grape-swagger (0.8.0) 44 | grape 45 | grape-entity 46 | hashie (3.4.3) 47 | i18n (0.7.0) 48 | ice_nine (0.11.2) 49 | json (1.8.3) 50 | multi_json (1.11.2) 51 | multi_xml (0.5.5) 52 | mysql2 (0.3.20) 53 | parser (2.3.0.2) 54 | ast (~> 2.2) 55 | pg (0.18.4) 56 | powerpack (0.1.1) 57 | rack (1.5.5) 58 | rack-accept (0.4.5) 59 | rack (>= 0.4) 60 | rack-cors (0.4.0) 61 | rack-mount (0.8.3) 62 | rack (>= 1.0.0) 63 | rack-test (0.6.3) 64 | rack (>= 1.0) 65 | racksh (1.0.0) 66 | rack (>= 1.0) 67 | rack-test (>= 0.5) 68 | rainbow (2.1.0) 69 | rake (10.3.2) 70 | rspec (3.4.0) 71 | rspec-core (~> 3.4.0) 72 | rspec-expectations (~> 3.4.0) 73 | rspec-mocks (~> 3.4.0) 74 | rspec-core (3.4.2) 75 | rspec-support (~> 3.4.0) 76 | rspec-expectations (3.4.0) 77 | diff-lcs (>= 1.2.0, < 2.0) 78 | rspec-support (~> 3.4.0) 79 | rspec-mocks (3.4.1) 80 | diff-lcs (>= 1.2.0, < 2.0) 81 | rspec-support (~> 3.4.0) 82 | rspec-support (3.4.1) 83 | rubocop (0.36.0) 84 | parser (>= 2.3.0.0, < 3.0) 85 | powerpack (~> 0.1) 86 | rainbow (>= 1.99.1, < 3.0) 87 | ruby-progressbar (~> 1.7) 88 | ruby-progressbar (1.7.5) 89 | schema_plus (1.5.3) 90 | activerecord (>= 3.2) 91 | valuable 92 | shotgun (0.9.1) 93 | rack (>= 1.0) 94 | thread_safe (0.3.5) 95 | tzinfo (0.3.46) 96 | valuable (0.9.10) 97 | virtus (1.0.5) 98 | axiom-types (~> 0.1) 99 | coercible (~> 1.0) 100 | descendants_tracker (~> 0.0, >= 0.0.3) 101 | equalizer (~> 0.0, >= 0.0.9) 102 | 103 | PLATFORMS 104 | ruby 105 | 106 | DEPENDENCIES 107 | activerecord (~> 3.2.22) 108 | activerecord-postgresql-adapter 109 | grape (~> 0.7.0) 110 | grape-swagger 111 | json 112 | mysql2 (~> 0.3.16) 113 | pg (~> 0.18.4) 114 | rack (~> 1.5.2) 115 | rack-cors 116 | rack-test 117 | racksh 118 | rake (~> 10.3.2) 119 | rspec 120 | rubocop 121 | schema_plus (~> 1.5.1) 122 | shotgun 123 | 124 | BUNDLED WITH 125 | 1.11.2 126 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | All rights are at (C) http://www.posty-soft.org 2013 2 | 3 | Developers: 4 | 5 | Florian Schmidhuber 6 | eMail: fschmidhuber@posty-soft.org 7 | 8 | Thomas Berendt 9 | eMail: tberendt@posty-soft.org 10 | 11 | Benjamin Heller 12 | eMail: bheller@posty-soft.org 13 | 14 | Lukas Weis 15 | eMail: lweis@posty-soft.org 16 | 17 | 18 | 19 | GNU LESSER GENERAL PUBLIC LICENSE 20 | Version 3, 29 June 2007 21 | 22 | Copyright (C) 2007 Free Software Foundation, Inc. 23 | Everyone is permitted to copy and distribute verbatim copies 24 | of this license document, but changing it is not allowed. 25 | 26 | 27 | This version of the GNU Lesser General Public License incorporates 28 | the terms and conditions of version 3 of the GNU General Public 29 | License, supplemented by the additional permissions listed below. 30 | 31 | 0. Additional Definitions. 32 | 33 | As used herein, "this License" refers to version 3 of the GNU Lesser 34 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 35 | General Public License. 36 | 37 | "The Library" refers to a covered work governed by this License, 38 | other than an Application or a Combined Work as defined below. 39 | 40 | An "Application" is any work that makes use of an interface provided 41 | by the Library, but which is not otherwise based on the Library. 42 | Defining a subclass of a class defined by the Library is deemed a mode 43 | of using an interface provided by the Library. 44 | 45 | A "Combined Work" is a work produced by combining or linking an 46 | Application with the Library. The particular version of the Library 47 | with which the Combined Work was made is also called the "Linked 48 | Version". 49 | 50 | The "Minimal Corresponding Source" for a Combined Work means the 51 | Corresponding Source for the Combined Work, excluding any source code 52 | for portions of the Combined Work that, considered in isolation, are 53 | based on the Application, and not on the Linked Version. 54 | 55 | The "Corresponding Application Code" for a Combined Work means the 56 | object code and/or source code for the Application, including any data 57 | and utility programs needed for reproducing the Combined Work from the 58 | Application, but excluding the System Libraries of the Combined Work. 59 | 60 | 1. Exception to Section 3 of the GNU GPL. 61 | 62 | You may convey a covered work under sections 3 and 4 of this License 63 | without being bound by section 3 of the GNU GPL. 64 | 65 | 2. Conveying Modified Versions. 66 | 67 | If you modify a copy of the Library, and, in your modifications, a 68 | facility refers to a function or data to be supplied by an Application 69 | that uses the facility (other than as an argument passed when the 70 | facility is invoked), then you may convey a copy of the modified 71 | version: 72 | 73 | a) under this License, provided that you make a good faith effort to 74 | ensure that, in the event an Application does not supply the 75 | function or data, the facility still operates, and performs 76 | whatever part of its purpose remains meaningful, or 77 | 78 | b) under the GNU GPL, with none of the additional permissions of 79 | this License applicable to that copy. 80 | 81 | 3. Object Code Incorporating Material from Library Header Files. 82 | 83 | The object code form of an Application may incorporate material from 84 | a header file that is part of the Library. You may convey such object 85 | code under terms of your choice, provided that, if the incorporated 86 | material is not limited to numerical parameters, data structure 87 | layouts and accessors, or small macros, inline functions and templates 88 | (ten or fewer lines in length), you do both of the following: 89 | 90 | a) Give prominent notice with each copy of the object code that the 91 | Library is used in it and that the Library and its use are 92 | covered by this License. 93 | 94 | b) Accompany the object code with a copy of the GNU GPL and this license 95 | document. 96 | 97 | 4. Combined Works. 98 | 99 | You may convey a Combined Work under terms of your choice that, 100 | taken together, effectively do not restrict modification of the 101 | portions of the Library contained in the Combined Work and reverse 102 | engineering for debugging such modifications, if you also do each of 103 | the following: 104 | 105 | a) Give prominent notice with each copy of the Combined Work that 106 | the Library is used in it and that the Library and its use are 107 | covered by this License. 108 | 109 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 110 | document. 111 | 112 | c) For a Combined Work that displays copyright notices during 113 | execution, include the copyright notice for the Library among 114 | these notices, as well as a reference directing the user to the 115 | copies of the GNU GPL and this license document. 116 | 117 | d) Do one of the following: 118 | 119 | 0) Convey the Minimal Corresponding Source under the terms of this 120 | License, and the Corresponding Application Code in a form 121 | suitable for, and under terms that permit, the user to 122 | recombine or relink the Application with a modified version of 123 | the Linked Version to produce a modified Combined Work, in the 124 | manner specified by section 6 of the GNU GPL for conveying 125 | Corresponding Source. 126 | 127 | 1) Use a suitable shared library mechanism for linking with the 128 | Library. A suitable mechanism is one that (a) uses at run time 129 | a copy of the Library already present on the user's computer 130 | system, and (b) will operate properly with a modified version 131 | of the Library that is interface-compatible with the Linked 132 | Version. 133 | 134 | e) Provide Installation Information, but only if you would otherwise 135 | be required to provide such information under section 6 of the 136 | GNU GPL, and only to the extent that such information is 137 | necessary to install and execute a modified version of the 138 | Combined Work produced by recombining or relinking the 139 | Application with a modified version of the Linked Version. (If 140 | you use option 4d0, the Installation Information must accompany 141 | the Minimal Corresponding Source and Corresponding Application 142 | Code. If you use option 4d1, you must provide the Installation 143 | Information in the manner specified by section 6 of the GNU GPL 144 | for conveying Corresponding Source.) 145 | 146 | 5. Combined Libraries. 147 | 148 | You may place library facilities that are a work based on the 149 | Library side by side in a single library together with other library 150 | facilities that are not Applications and are not covered by this 151 | License, and convey such a combined library under terms of your 152 | choice, if you do both of the following: 153 | 154 | a) Accompany the combined library with a copy of the same work based 155 | on the Library, uncombined with any other library facilities, 156 | conveyed under the terms of this License. 157 | 158 | b) Give prominent notice with the combined library that part of it 159 | is a work based on the Library, and explaining where to find the 160 | accompanying uncombined form of the same work. 161 | 162 | 6. Revised Versions of the GNU Lesser General Public License. 163 | 164 | The Free Software Foundation may publish revised and/or new versions 165 | of the GNU Lesser General Public License from time to time. Such new 166 | versions will be similar in spirit to the present version, but may 167 | differ in detail to address new problems or concerns. 168 | 169 | Each version is given a distinguishing version number. If the 170 | Library as you received it specifies that a certain numbered version 171 | of the GNU Lesser General Public License "or any later version" 172 | applies to it, you have the option of following the terms and 173 | conditions either of that published version or of any later version 174 | published by the Free Software Foundation. If the Library as you 175 | received it does not specify a version number of the GNU Lesser 176 | General Public License, you may choose any version of the GNU Lesser 177 | General Public License ever published by the Free Software Foundation. 178 | 179 | If the Library as you received it specifies that a proxy can decide 180 | whether future versions of the GNU Lesser General Public License shall 181 | apply, that proxy's public statement of acceptance of any version is 182 | permanent authorization for you to choose that version for the 183 | Library. -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bundle exec rackup config.ru -p $PORT -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #posty\_API 2 | [![Build Status](https://travis-ci.org/posty/posty_api.svg?branch=master)](https://travis-ci.org/posty/posty_api) 3 | 4 | The posty\_API is the core element of the posty softwarestack. It is developed to administrate a mailserver based on Postfix and Dovecot. It offers an easy REST interface which can be used in own applications or with the posty client applications, posty\_CLI and posty\_webUI. 5 | 6 | ## Requirements 7 | 8 | You need a working ruby installation. 9 | 10 | Tested with ruby 2.1.8, 2.2.4, 2.3.0 11 | 12 | ## Installation 13 | 14 | 1. Download the source either using git or from the GitHub page as archive. 15 | 2. Extract the archive 16 | 3. Change directory to the extracted folder 17 | 4. Copy config/database.mysql2.yml or config/database.postgresql.yml to config/database.yml and change it to your needs. 18 | 5. Run ``bundle install --with mysql`` for MySQL or ``bundle install --with postgresql`` for PostgreSQL 19 | 6. Run ``rake db:migrate`` 20 | 7. Run ``rake api_key:generate`` 21 | 8. Start the application e.g. with ``rackup`` 22 | 23 | Notice: Check your RACK_ENV if any problems occur. 24 | 25 | ## Usage 26 | 27 | Here is a short overview about the possible API REST calls. 28 | Also available at [http://www.posty-soft.de/swaggerv2/posty_api.html](http://www.posty-soft.org/swaggerv2/posty_api.html#!/api) 29 | 30 | **Domains:** 31 | 32 | * **GET** - http://API-URL/api/v1/domains - get all domains 33 | * **GET** - http://API-URL/api/v1/domains/{name} - get {name} domain 34 | * **POST** - http://API-URL/api/v1/domains - create domain (params: name) 35 | * **PUT** - http://API-URL/api/v1/domains/{name} - change domain {name} (params: name) 36 | * **DELETE** - http://API-URL/api/v1/domains/{name} - delete domain {name} 37 | 38 | **Users:** 39 | 40 | * **GET** - http://API-URL/api/v1/domains/{domain}/users - get all users for {domain} 41 | * **GET** - http://API-URL/api/v1/domains/{domain}/users/{name} - get the user {name}@{domain} 42 | * **POST** - http://API-URL/api/v1/domains/{domain}/users - create user (params: name, password, quota) 43 | * **PUT** - http://API-URL/api/v1/domains/{domain}/users/{name} - change user {name}@{domain} (params: name, password, quota) 44 | * **DELETE** - http://API-URL/api/v1/domains/{domain}/users/{name} - delete user {name}@{domain} 45 | 46 | **UserAliases:** 47 | 48 | * **GET** - http://API-URL/api/v1/domains/{domain}/users/{user}/aliases - get all aliases for {user} 49 | * **GET** - http://API-URL/api/v1/domains/{domain}/users/{user}/aliases/{name} - get the alias {name}@{domain} 50 | * **POST** - http://API-URL/api/v1/domains/{domain}/users/{user}/aliases - create alias (params: name) 51 | * **PUT** - http://API-URL/api/v1/domains/{domain}/users/{user}/aliases/{name} - change alias {name}@{domain} (params: name) 52 | * **DELETE** - http://API-URL/api/v1/domains/{domain}/users/{user}/aliases/{name} - delete alias {name}@{domain} 53 | 54 | **DomainAliases:** 55 | 56 | * **GET** - http://API-URL/api/v1/domains/{domain}/aliases - get all aliases for {domain} 57 | * **GET** - http://API-URL/api/v1/domains/{domain}/aliases/{name} - get the alias @{name} 58 | * **POST** - http://API-URL/api/v1/domains/{domain}/aliases - create alias (params: name) 59 | * **PUT** - http://API-URL/api/v1/domains/{domain}/aliases/{name} - change alias @{name} (params: name) 60 | * **DELETE** - http://API-URL/api/v1/domains/{domain}/aliases/{name} - delete alias @{name} 61 | 62 | **Summary:** 63 | 64 | * **GET** - http://API-URL/api/v1/summary - get the number of existing domains, users, domain aliases and user aliases 65 | 66 | **Transports:** 67 | 68 | * **GET** - http://API-URL/api/v1/transports - get all transports 69 | * **GET** - http://API-URL/api/v1/transports/{name} - get the transport for {name} 70 | * **POST** - http://API-URL/api/v1/transports - create alias (params: name, destination) 71 | * **PUT** - http://API-URL/api/v1/transports/{name} - change transport {name} (params: name, destination) 72 | * **DELETE** - http://API-URL/api/v1/transports/{name} - delete transport {name} 73 | 74 | **ApiKeys:** 75 | 76 | * **GET** - http://API-URL/api/v1/api_keys - get all api keys 77 | * **GET** - http://API-URL/api/v1/api_keys/{token} - get the api_key for {token} 78 | * **POST** - http://API-URL/api/v1/api_keys - create access_token (params: expires_at) 79 | * **PUT** - http://API-URL/api/v1/api_keys/{token} - change api_key {token} (params: active, expires_at) 80 | * **DELETE** - http://API-URL/api/v1/api_keys/{token} - delete access_token {token} 81 | 82 | 83 | :access_token :active :expires_at 84 | 85 | ## Test 86 | 87 | You can run the tests by going to project root and run: 88 | ``rspec`` 89 | 90 | ## Information 91 | 92 | For more informations about posty please visit our website: 93 | [www.posty-soft.org](http://www.posty-soft.org) 94 | 95 | ## Support 96 | 97 | 98 | * Email: 99 | * support@posty-soft.org 100 | 101 | ### Bug reports 102 | 103 | If you discover any bugs, feel free to create an issue on GitHub. Please add as much information as possible to help us fixing the possible bug. We also encourage you to help even more by forking and sending us a pull request. 104 | 105 | ### License 106 | 107 | LGPL v3 license. See LICENSE for details. 108 | 109 | ### Copyright 110 | 111 | All rights are at (C) [http://www.posty-soft.org](http://www.posty-soft.org) 2014 112 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | begin 2 | require 'rspec/core/rake_task' 3 | RSpec::Core::RakeTask.new :spec 4 | task default: :spec 5 | rescue LoadError 6 | end 7 | 8 | 9 | task :environment do 10 | require File.expand_path('../config/environment', __FILE__) 11 | end 12 | 13 | namespace :api_key do 14 | desc 'Creates a new api key' 15 | task generate: :environment do 16 | puts ApiKey.create(expires_at: Time.now + 100.years).access_token 17 | end 18 | end 19 | 20 | namespace :db do 21 | desc 'Migrate the database through scripts in db/migrate' 22 | task(migrate: :environment) do 23 | ActiveRecord::Migrator.migrate('db/migrate', ENV['VERSION'] ? ENV['VERSION'].to_i : nil) 24 | Rake::Task['db:schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby 25 | end 26 | 27 | namespace :migrate do 28 | desc 'Runs the "down" for a given migration VERSION' 29 | task(down: :environment) do 30 | ActiveRecord::Migrator.down('db/migrate', ENV['VERSION'] ? ENV['VERSION'].to_i : nil) 31 | Rake::Task['db:schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby 32 | end 33 | 34 | desc 'Runs the "up" for a given migration VERSION' 35 | task(up: :environment) do 36 | ActiveRecord::Migrator.up('db/migrate', ENV['VERSION'] ? ENV['VERSION'].to_i : nil) 37 | Rake::Task['db:schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby 38 | end 39 | 40 | desc 'Rollbacks the database one migration and re migrate up' 41 | task(redo: :environment) do 42 | ActiveRecord::Migrator.rollback('db/migrate', 1) 43 | ActiveRecord::Migrator.up('db/migrate', nil) 44 | Rake::Task['db:schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby 45 | end 46 | end 47 | 48 | namespace :schema do 49 | task dump: :environment do 50 | require 'active_record/schema_dumper' 51 | File.open(ENV['SCHEMA'] || 'db/schema.rb', 'w') do |file| 52 | ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file) 53 | end 54 | end 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /app/api/api.rb: -------------------------------------------------------------------------------- 1 | require 'grape-swagger' 2 | 3 | module Posty 4 | class API < Grape::API 5 | prefix 'api' 6 | format :json 7 | rescue_from :all 8 | 9 | helpers APIHelper 10 | 11 | mount ::Posty::API_v1 12 | 13 | add_swagger_documentation mount_path: 'v1/swagger_doc', api_version: 'v1' 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/api/helper.rb: -------------------------------------------------------------------------------- 1 | module Posty 2 | module APIHelper 3 | def attributes_for_keys(keys) 4 | attrs = {} 5 | keys.each do |key| 6 | attrs[key] = params[key] if params[key].present? 7 | end 8 | attrs 9 | end 10 | 11 | def ensure_entity(message = '', &_block) 12 | entity = yield 13 | 14 | error!("unknown #{message}", 404) unless entity 15 | 16 | entity 17 | end 18 | 19 | def return_on_success(entity, &_block) 20 | success = yield entity 21 | 22 | success ? entity : validation_error(entity.errors) 23 | end 24 | 25 | # rubocop:disable Metrics/LineLength 26 | def get_summary(entitys = { 'VirtualDomains' => 'Domains', 'VirtualUsers' => 'Users', 'VirtualUserAliases' => 'User Aliases', 'VirtualDomainAliases' => 'Domain Aliases' }) 27 | summary = [] 28 | 29 | entitys.sort.each do |clazz, name| 30 | summary << { 'name' => name, 'count' => clazz.classify.constantize.all.count } 31 | end 32 | 33 | summary 34 | end 35 | # rubocop:enable Metrics/LineLength 36 | 37 | def authenticate! 38 | error!('Unauthorized. Invalid or expired token.', 401) unless current_session 39 | end 40 | 41 | def current_session 42 | auth_token = params[:auth_token] || env['HTTP_AUTH_TOKEN'] 43 | @current_session ||= ApiKey.active.where(access_token: auth_token).first 44 | end 45 | 46 | def current_domain 47 | @current_domain ||= ensure_entity('Domain') do 48 | VirtualDomain.find_by_name(params[:domain_name]) 49 | end 50 | end 51 | 52 | def current_user 53 | ensure_entity('User') do 54 | current_domain.virtual_users.find_by_name(params[:user_name]) 55 | end 56 | end 57 | 58 | def current_transport 59 | ensure_entity('Transport') do 60 | VirtualTransport.find_by_name(params[:transport_name]) 61 | end 62 | end 63 | 64 | def current_user_alias 65 | ensure_entity('UserAlias') do 66 | current_user.virtual_user_aliases.find_by_name(params[:alias_name]) 67 | end 68 | end 69 | 70 | def current_domain_alias 71 | ensure_entity('DomainAlias') do 72 | current_domain.virtual_domain_aliases.find_by_name(params[:alias_name]) 73 | end 74 | end 75 | 76 | def current_domain_id_hash 77 | { 'virtual_domain_id' => current_domain.id } 78 | end 79 | 80 | def current_user_id_hash 81 | { 'virtual_user_id' => current_user.id } 82 | end 83 | 84 | def current_api_key 85 | ensure_entity('ApiKey') do 86 | ApiKey.find_by_access_token(params[:api_key]) 87 | end 88 | end 89 | 90 | def complete_email_address(user, domain) 91 | "#{user}@#{domain}" 92 | end 93 | 94 | def validation_error(errors) 95 | error!(errors, 400) 96 | end 97 | end 98 | end 99 | -------------------------------------------------------------------------------- /app/api/v1.rb: -------------------------------------------------------------------------------- 1 | module Posty 2 | # rubocop:disable ClassAndModuleCamelCase 3 | class API_v1 < Grape::API 4 | version 'v1', using: :path, vendor: 'posty' 5 | before { authenticate! } 6 | 7 | resource :api_keys do 8 | desc 'Returns all available API Keys' 9 | get do 10 | ApiKey.all 11 | end 12 | 13 | desc 'Creates a new API Key' 14 | post do 15 | ApiKey.create(attributes_for_keys([:expires_at])) 16 | end 17 | 18 | segment '/:api_key' do 19 | desc 'Returns the information to the specified api_key' 20 | get do 21 | current_api_key 22 | end 23 | 24 | desc 'Update the specified api_key' 25 | put do 26 | return_on_success(current_api_key) do |api_key| 27 | api_key.update_attributes(attributes_for_keys([:active, :expires_at])) 28 | end 29 | end 30 | 31 | desc 'Delete the given token' 32 | delete do 33 | current_api_key.destroy 34 | end 35 | end 36 | end 37 | 38 | resource :summary do 39 | desc 'Returns a summary of all Resources' 40 | get do 41 | get_summary 42 | end 43 | end 44 | 45 | resource :transports do 46 | desc 'Returns all available transports' 47 | get do 48 | VirtualTransport.all 49 | end 50 | 51 | desc 'Create new transport' 52 | post do 53 | @transport = VirtualTransport.new(attributes_for_keys([:name, :destination])) 54 | @transport.save ? @transport : validation_error(@transport.errors) 55 | end 56 | 57 | segment '/:transport_name', requirements: { transport_name: /([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}/ } do 58 | desc 'Returns the information to the specified transport' 59 | get do 60 | current_transport 61 | end 62 | 63 | desc 'Update the specified transport' 64 | put do 65 | return_on_success(current_transport) do |transport| 66 | transport.update_attributes(attributes_for_keys([:name, :destination])) 67 | end 68 | end 69 | 70 | desc 'Delete the specified transport' 71 | delete do 72 | current_transport.destroy 73 | end 74 | end 75 | end 76 | 77 | resource :domains do 78 | desc 'Returns all available domains' 79 | get do 80 | VirtualDomain.all 81 | end 82 | 83 | desc 'Create new domain' 84 | post do 85 | @domain = VirtualDomain.new(attributes_for_keys([:name])) 86 | @domain.save ? @domain : validation_error(@domain.errors) 87 | end 88 | 89 | segment '/:domain_name', requirements: { domain_name: /([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}/ } do 90 | desc 'Returns the information to the specified domain' 91 | get do 92 | current_domain 93 | end 94 | 95 | desc 'Update the specified domain' 96 | put do 97 | return_on_success(current_domain) do |domain| 98 | domain.update_attributes(attributes_for_keys([:name])) 99 | end 100 | end 101 | 102 | desc 'Delete the specified domain' 103 | delete do 104 | current_domain.destroy 105 | end 106 | 107 | resource '/users' do 108 | desc 'Returns all users for the specified domain' 109 | get do 110 | current_domain.virtual_users 111 | end 112 | 113 | desc 'Create new user' 114 | post do 115 | @user = VirtualUser.new(current_domain_id_hash.merge(attributes_for_keys([:name, :password, :quota]))) 116 | @user.save ? @user : validation_error(@user.errors) 117 | end 118 | 119 | segment '/:user_name', requirements: { user_name: /[a-z0-9\-\.\_]+/ } do 120 | desc 'Returns the information to the specified user' 121 | get do 122 | current_user 123 | end 124 | 125 | desc 'Update the specified user' 126 | put do 127 | return_on_success(current_user) do |user| 128 | user.update_attributes(attributes_for_keys([:name, :password, :quota])) 129 | end 130 | end 131 | 132 | desc 'Delete the specified user' 133 | delete do 134 | current_user.destroy 135 | end 136 | 137 | resource '/aliases' do 138 | desc 'Returns all aliases for the specified user' 139 | get do 140 | current_user.virtual_user_aliases 141 | end 142 | 143 | desc 'Create new user alias' 144 | post do 145 | @alias = VirtualUserAlias.new(current_user_id_hash.merge(attributes_for_keys([:name]))) 146 | @alias.save ? @alias : validation_error(@alias.errors) 147 | end 148 | 149 | segment '/:alias_name', requirements: { alias_name: /[a-z0-9\-\.\_]+/ } do 150 | desc 'Returns the information to the specified user alias' 151 | get do 152 | current_user_alias 153 | end 154 | 155 | desc 'Update the specified user alias' 156 | put do 157 | return_on_success(current_user_alias) do |user_alias| 158 | user_alias.update_attributes(attributes_for_keys([:name])) 159 | end 160 | end 161 | 162 | desc 'Delete the specified user alias' 163 | delete do 164 | current_user_alias.destroy 165 | end 166 | end 167 | end 168 | end 169 | end 170 | 171 | resource '/aliases' do 172 | desc 'Returns all aliases for the specified domain' 173 | get do 174 | current_domain.virtual_domain_aliases 175 | end 176 | 177 | desc 'Create new domain alias' 178 | post do 179 | @alias = VirtualDomainAlias.new(current_domain_id_hash.merge(attributes_for_keys([:name]))) 180 | @alias.save ? @alias : validation_error(@alias.errors) 181 | end 182 | 183 | segment '/:alias_name', requirements: { alias_name: /([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}/ } do 184 | desc 'Returns the information to the specified domain alias' 185 | get do 186 | current_domain_alias 187 | end 188 | 189 | desc 'Update the specified domain alias' 190 | put do 191 | return_on_success(current_domain_alias) do |domain_alias| 192 | domain_alias.update_attributes(attributes_for_keys([:name])) 193 | end 194 | end 195 | 196 | desc 'Delete the specified domain alias' 197 | delete do 198 | current_domain_alias.destroy 199 | end 200 | end 201 | end 202 | end 203 | end 204 | end 205 | end 206 | -------------------------------------------------------------------------------- /app/models/api_key.rb: -------------------------------------------------------------------------------- 1 | class ApiKey < ActiveRecord::Base 2 | attr_accessible :access_token, :expires_at, :active, :application 3 | before_create :generate_access_token 4 | 5 | validates :expires_at, presence: true 6 | validates :access_token, uniqueness: true 7 | 8 | scope :active, -> { where('expires_at > ? AND active = ?', Time.now, true) } 9 | 10 | private 11 | 12 | # rubocop:disable Loop 13 | def generate_access_token 14 | begin 15 | self.access_token = SecureRandom.hex 16 | end while self.class.exists?(access_token: access_token) 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /app/models/folder.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module Folder 3 | MAIL_ROOT_FOLDER = '/srv/vmail'.freeze 4 | MAIL_USER = 'vmail'.freeze 5 | MAIL_GROUP = MAIL_USER 6 | STORAGE_CLASS = 'mdbox/storage'.freeze # Possible values "mdbox", "Maildir", "mbox" 7 | 8 | def move_folder 9 | if ENV['RACK_ENV'] == 'production' 10 | if File.directory?(get_folder(name_change.last)) 11 | error!('A folder with this name already exists.', 400) 12 | else 13 | FileUtils.mv get_folder(name_change.first), get_folder(name_change.last) 14 | end 15 | end 16 | end 17 | 18 | def remove_folder 19 | FileUtils.rm_rf get_folder if ENV['RACK_ENV'] == 'production' 20 | end 21 | 22 | def change_permissions(folder_array) 23 | current_folder = '' 24 | folder_array.each do |folder| 25 | current_folder += folder + '/' 26 | FileUtils.chown MAIL_USER, MAIL_GROUP, MAIL_ROOT_FOLDER + '/' + current_folder 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /app/models/virtual_domain.rb: -------------------------------------------------------------------------------- 1 | require 'folder' 2 | 3 | class VirtualDomain < ActiveRecord::Base 4 | include Folder 5 | 6 | has_many :virtual_users, dependent: :destroy 7 | has_many :virtual_domain_aliases, dependent: :destroy 8 | 9 | validates :name, uniqueness: true 10 | validates :name, presence: true 11 | validates :name, format: { with: /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/, message: 'Please use a valid domain name' } 12 | validate :name_unique 13 | 14 | after_update :move_folder, if: :name_changed? 15 | after_destroy :remove_folder 16 | 17 | def name_unique 18 | return unless VirtualDomainAlias.where('name = ?', name).exists? 19 | 20 | errors[:name] << 'A domain alias with this name already exists' 21 | end 22 | 23 | def get_folder(domain = name) 24 | MAIL_ROOT_FOLDER + '/' + domain 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /app/models/virtual_domain_alias.rb: -------------------------------------------------------------------------------- 1 | class VirtualDomainAlias < ActiveRecord::Base 2 | belongs_to :virtual_domain 3 | 4 | validates :name, uniqueness: true 5 | validates :name, presence: true 6 | validates :name, format: { with: /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/, message: 'Please use a valid domain name' } 7 | validates :virtual_domain_id, presence: true 8 | validate :name_unique 9 | 10 | def name_unique 11 | return unless VirtualDomain.where('name = ?', name).exists? 12 | 13 | errors[:name] << 'A domain with this name already exists' 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/models/virtual_transport.rb: -------------------------------------------------------------------------------- 1 | class VirtualTransport < ActiveRecord::Base 2 | validates :name, uniqueness: true 3 | validates :name, presence: true 4 | validates :name, format: { with: /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/, message: 'Please use a valid domain name' } 5 | validates :destination, presence: true 6 | end 7 | -------------------------------------------------------------------------------- /app/models/virtual_user.rb: -------------------------------------------------------------------------------- 1 | require 'digest/sha2' 2 | require 'folder' 3 | 4 | class VirtualUser < ActiveRecord::Base 5 | include Folder 6 | 7 | belongs_to :virtual_domain 8 | has_many :virtual_user_aliases, dependent: :destroy 9 | 10 | validates :name, uniqueness: { scope: :virtual_domain_id } 11 | validates :name, format: { with: /^[a-z0-9\-\.\_]+$/, message: 'Please use a valid user name' } 12 | validates :name, presence: true 13 | validates :password, presence: true, length: { minimum: 5 } 14 | validates :virtual_domain_id, presence: true 15 | # validate :name_unique 16 | 17 | before_save :hash_password, if: :password_changed? 18 | after_create :create_folder 19 | after_update :move_folder, if: :name_changed? 20 | after_destroy :remove_folder 21 | 22 | # TODO: fix name_unique virtual_domain_id is not present 23 | def name_unique 24 | if VirtualUserAlias.where('name = ? and virtual_domain_id = ?', name, virtual_domain.id).exists? 25 | errors[:email] << 'A alias with this address already exist' 26 | end 27 | end 28 | 29 | def hash_password 30 | self.password = password.crypt("$6$#{SecureRandom.hex(10)}") 31 | end 32 | 33 | def get_folder(user = name) 34 | MAIL_ROOT_FOLDER + '/' + virtual_domain.name + '/' + user 35 | end 36 | 37 | def create_folder 38 | complete_path = get_folder + '/' + STORAGE_CLASS 39 | folder_array = complete_path.gsub(MAIL_ROOT_FOLDER + '/', '').split('/') 40 | 41 | if ENV['RACK_ENV'] == 'production' 42 | if File.directory?(get_folder) 43 | error!('A folder with this name already exists.', 400) 44 | else 45 | FileUtils.mkdir_p complete_path 46 | change_permissions(folder_array) 47 | end 48 | end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /app/models/virtual_user_alias.rb: -------------------------------------------------------------------------------- 1 | class VirtualUserAlias < ActiveRecord::Base 2 | belongs_to :virtual_user 3 | 4 | # TODO: name uniqueness with scope is nonsense 5 | validates :name, uniqueness: { scope: :virtual_user_id } 6 | 7 | validates :name, presence: true 8 | validates :name, format: { with: /^[a-z0-9\-\.\_]+$/, message: 'Please use a valid source' } 9 | validates :virtual_user_id, presence: true 10 | # validate :name_unique 11 | 12 | def name_unique 13 | if VirtualUser.where('name = ? and virtual_domain_id = ?', name, virtual_domain_id).exists? 14 | errors[:source] << 'A account with this address already exist' 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | require File.expand_path('../config/environment', __FILE__) 2 | 3 | use Rack::Cors do 4 | allow do 5 | origins '*' 6 | resource '*', headers: :any, methods: [:put, :delete, :get, :post, :options] 7 | end 8 | end 9 | 10 | run Posty::API 11 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'app', 'api')) 2 | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'app', 'models')) 3 | $LOAD_PATH.unshift(File.dirname(__FILE__)) 4 | 5 | require 'boot' 6 | require 'uri' 7 | require 'erb' 8 | 9 | Bundler.require :default, ENV['RACK_ENV'] 10 | 11 | dbconfig = YAML.load(ERB.new(File.read(Dir.pwd + '/config/database.yml')).result) 12 | ActiveRecord::Base.establish_connection(dbconfig[ENV['RACK_ENV']]) 13 | 14 | I18n.config.enforce_available_locales = false 15 | 16 | Dir[File.expand_path('../../app/api/v*.rb', __FILE__)].each do |f| 17 | require f 18 | end 19 | 20 | Dir[File.expand_path('../../app/models/*.rb', __FILE__)].each do |f| 21 | require f 22 | end 23 | 24 | require 'helper' 25 | require 'api' 26 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | require 'bundler/setup' 3 | -------------------------------------------------------------------------------- /config/database.mysql2.yml: -------------------------------------------------------------------------------- 1 | production: 2 | adapter: mysql2 3 | encoding: utf8 4 | reconnect: false 5 | database: database_name 6 | pool: 5 7 | username: database_user_name 8 | password: database_user_password 9 | socket: mysql socket path (/var/mysql/mysql.sock) 10 | 11 | development: 12 | adapter: mysql2 13 | encoding: utf8 14 | reconnect: false 15 | database: database_name 16 | pool: 5 17 | username: database_user_name 18 | password: database_user_password 19 | socket: mysql socket path (/var/mysql/mysql.sock) -------------------------------------------------------------------------------- /config/database.postgresql.yml: -------------------------------------------------------------------------------- 1 | production: 2 | adapter: postgresql 3 | encoding: utf8 4 | reconnect: false 5 | database: database_name 6 | pool: 5 7 | username: database_user_name 8 | password: database_user_password 9 | host: localhost 10 | 11 | development: 12 | adapter: postgresql 13 | encoding: utf8 14 | reconnect: false 15 | database: database_name 16 | pool: 5 17 | username: database_user_name 18 | password: database_user_password 19 | host: localhost -------------------------------------------------------------------------------- /config/database.travis.mysql2.yml: -------------------------------------------------------------------------------- 1 | test: 2 | adapter: mysql2 3 | database: posty_api_test 4 | username: travis 5 | encoding: utf8 6 | -------------------------------------------------------------------------------- /config/database.travis.postgresql.yml: -------------------------------------------------------------------------------- 1 | test: 2 | adapter: postgresql 3 | database: posty_api_test 4 | username: postgres -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | ENV['RACK_ENV'] ||= 'development' 2 | 3 | require File.expand_path('../application', __FILE__) 4 | -------------------------------------------------------------------------------- /db/migrate/20130502150649_create_virtual_domains.rb: -------------------------------------------------------------------------------- 1 | class CreateVirtualDomains < ActiveRecord::Migration 2 | def self.up 3 | create_table :virtual_domains do |t| 4 | t.string :name 5 | t.timestamps 6 | end 7 | end 8 | 9 | def self.down 10 | drop_table :virtual_domains 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20130502151649_create_virtual_users.rb: -------------------------------------------------------------------------------- 1 | class CreateVirtualUsers < ActiveRecord::Migration 2 | def self.up 3 | create_table :virtual_users do |t| 4 | t.integer :virtual_domain_id 5 | t.string :password 6 | t.string :name 7 | t.timestamps 8 | end 9 | end 10 | 11 | def self.down 12 | drop_table :virtual_users 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /db/migrate/20130502152649_create_virtual_aliases.rb: -------------------------------------------------------------------------------- 1 | class CreateVirtualAliases < ActiveRecord::Migration 2 | def self.up 3 | create_table :virtual_aliases do |t| 4 | t.integer :virtual_domain_id 5 | t.string :source 6 | t.string :destination 7 | t.timestamps 8 | end 9 | end 10 | 11 | def self.down 12 | drop_table :virtual_aliases 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /db/migrate/20130614141749_add_views.rb: -------------------------------------------------------------------------------- 1 | class AddViews < ActiveRecord::Migration 2 | def self.up 3 | create_view :users_view, "select Concat(virtual_users.name, '@', virtual_domains.name) as email, password from virtual_users, virtual_domains where virtual_users.virtual_domain_id = virtual_domains.id" 4 | create_view :aliases_view, "select Concat(virtual_aliases.source, '@', virtual_domains.name) as source, Concat(virtual_aliases.destination, '@', virtual_domains.name) as destination from virtual_aliases, virtual_domains where virtual_aliases.virtual_domain_id = virtual_domains.id" 5 | end 6 | 7 | def self.down 8 | drop_view :users_view 9 | drop_view :aliases_view 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /db/migrate/20130809200149_create_virtual_domain_aliases.rb: -------------------------------------------------------------------------------- 1 | class CreateVirtualDomainAliases < ActiveRecord::Migration 2 | def self.up 3 | create_table :virtual_domain_aliases do |t| 4 | t.integer :virtual_domain_id 5 | t.string :name 6 | t.timestamps 7 | end 8 | end 9 | 10 | def self.down 11 | drop_table :virtual_domain_aliases 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /db/migrate/20130809200249_add_domain_aliases_views.rb: -------------------------------------------------------------------------------- 1 | class AddDomainAliasesViews < ActiveRecord::Migration 2 | def self.up 3 | create_view :domain_aliases_view, "select Concat('@', virtual_domain_aliases.name) as source, Concat('@', virtual_domains.name) as destination from virtual_domain_aliases, virtual_domains where virtual_domain_aliases.virtual_domain_id = virtual_domains.id" 4 | end 5 | 6 | def self.down 7 | drop_view :domain_aliases_view 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /db/migrate/20130812172949_create_user_aliases.rb: -------------------------------------------------------------------------------- 1 | class CreateUserAliases < ActiveRecord::Migration 2 | def self.up 3 | create_table :virtual_user_aliases do |t| 4 | t.integer :virtual_user_id 5 | t.string :name 6 | t.timestamps 7 | end 8 | 9 | drop_view :aliases_view 10 | drop_table :virtual_aliases 11 | end 12 | 13 | def self.down 14 | drop_table :virtual_user_aliases 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /db/migrate/20130812182949_create_user_aliases_view.rb: -------------------------------------------------------------------------------- 1 | class CreateUserAliasesView < ActiveRecord::Migration 2 | def self.up 3 | create_view :user_aliases_view, "select Concat(virtual_user_aliases.name, '@', virtual_domains.name) as source, Concat(virtual_users.name, '@', virtual_domains.name) as destination from virtual_user_aliases, virtual_users, virtual_domains where virtual_users.virtual_domain_id = virtual_domains.id AND virtual_user_aliases.virtual_user_id = virtual_users.id" 4 | end 5 | 6 | def self.down 7 | drop_view :user_aliases_view 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /db/migrate/20130812184615_add_quota_to_virtual_users.rb: -------------------------------------------------------------------------------- 1 | class AddQuotaToVirtualUsers < ActiveRecord::Migration 2 | def self.up 3 | add_column :virtual_users, :quota, :integer, :limit => 8, :default => 0 4 | end 5 | 6 | def self.down 7 | remove_column :virtual_users, :quota 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /db/migrate/20130813150649_create_virtual_transports.rb: -------------------------------------------------------------------------------- 1 | class CreateVirtualTransports < ActiveRecord::Migration 2 | def self.up 3 | create_table :virtual_transports do |t| 4 | t.string :name 5 | t.string :destination 6 | t.timestamps 7 | end 8 | end 9 | 10 | def self.down 11 | drop_table :virtual_transports 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /db/migrate/20130813181249_create_api_keys.rb: -------------------------------------------------------------------------------- 1 | class CreateApiKeys < ActiveRecord::Migration 2 | def self.up 3 | create_table :api_keys do |t| 4 | t.string :access_token, null: false 5 | t.boolean :active, null: false, default: true 6 | t.datetime :expires_at 7 | t.timestamps 8 | end 9 | end 10 | 11 | def self.down 12 | drop_table :api_keys 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /db/migrate/20130826162949_add_quota_to_users_view.rb: -------------------------------------------------------------------------------- 1 | class AddQuotaToUsersView < ActiveRecord::Migration 2 | def self.up 3 | drop_view :users_view 4 | create_view :users_view, "select Concat(virtual_users.name, '@', virtual_domains.name) as email, password, quota from virtual_users, virtual_domains where virtual_users.virtual_domain_id = virtual_domains.id" 5 | end 6 | 7 | def self.down 8 | drop_view :users_view 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20150508142715_migrate_user_quota_to_mb.rb: -------------------------------------------------------------------------------- 1 | class MigrateUserQuotaToMb < ActiveRecord::Migration 2 | MEGABYTE = 1024.0 * 1024.0 3 | 4 | def self.up 5 | VirtualUser.all do |user| 6 | user.quota = user.quota / MEGABYTE 7 | user.save! 8 | end 9 | end 10 | 11 | def self.down 12 | VirtualUser.all do |user| 13 | user.quota = user.quota * MEGABYTE 14 | user.save! 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /db/migrate/20150519141623_add_indexes.rb: -------------------------------------------------------------------------------- 1 | class AddIndexes < ActiveRecord::Migration 2 | def self.up 3 | add_index :api_keys, :access_token 4 | add_index :virtual_domain_aliases, :virtual_domain_id 5 | add_index :virtual_domain_aliases, :name 6 | add_index :virtual_domains, :name 7 | add_index :virtual_transports, :name 8 | add_index :virtual_user_aliases, :virtual_user_id 9 | add_index :virtual_user_aliases, :name 10 | add_index :virtual_users, :virtual_domain_id 11 | add_index :virtual_users, :name 12 | end 13 | 14 | def self.down 15 | remove_index :api_keys, :access_token 16 | remove_index :virtual_domain_aliases, :virtual_domain_id 17 | remove_index :virtual_domain_aliases, :name 18 | remove_index :virtual_domains, :name 19 | remove_index :virtual_transports, :name 20 | remove_index :virtual_user_aliases, :virtual_user_id 21 | remove_index :virtual_user_aliases, :name 22 | remove_index :virtual_users, :virtual_domain_id 23 | remove_index :virtual_users, :name 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended to check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(:version => 20150519141623) do 14 | 15 | create_table "api_keys", :force => true do |t| 16 | t.string "access_token", :null => false 17 | t.boolean "active", :default => true, :null => false 18 | t.datetime "expires_at" 19 | t.datetime "created_at", :null => false 20 | t.datetime "updated_at", :null => false 21 | t.index ["access_token"], :name => "index_api_keys_on_access_token" 22 | end 23 | 24 | create_table "virtual_domain_aliases", :force => true do |t| 25 | t.integer "virtual_domain_id" 26 | t.string "name" 27 | t.datetime "created_at", :null => false 28 | t.datetime "updated_at", :null => false 29 | t.index ["name"], :name => "index_virtual_domain_aliases_on_name" 30 | t.index ["virtual_domain_id"], :name => "index_virtual_domain_aliases_on_virtual_domain_id" 31 | end 32 | 33 | create_table "virtual_domains", :force => true do |t| 34 | t.string "name" 35 | t.datetime "created_at", :null => false 36 | t.datetime "updated_at", :null => false 37 | t.index ["name"], :name => "index_virtual_domains_on_name" 38 | end 39 | 40 | create_view "domain_aliases_view", "select concat('@',`virtual_domain_aliases`.`name`) AS `source`,concat('@',`virtual_domains`.`name`) AS `destination` from `virtual_domain_aliases` join `virtual_domains` where (`virtual_domain_aliases`.`virtual_domain_id` = `virtual_domains`.`id`)", :force => true 41 | create_table "virtual_user_aliases", :force => true do |t| 42 | t.integer "virtual_user_id" 43 | t.string "name" 44 | t.datetime "created_at", :null => false 45 | t.datetime "updated_at", :null => false 46 | t.index ["name"], :name => "index_virtual_user_aliases_on_name" 47 | t.index ["virtual_user_id"], :name => "index_virtual_user_aliases_on_virtual_user_id" 48 | end 49 | 50 | create_table "virtual_users", :force => true do |t| 51 | t.integer "virtual_domain_id" 52 | t.string "password" 53 | t.string "name" 54 | t.datetime "created_at", :null => false 55 | t.datetime "updated_at", :null => false 56 | t.integer "quota", :limit => 8, :default => 0 57 | t.index ["name"], :name => "index_virtual_users_on_name" 58 | t.index ["virtual_domain_id"], :name => "index_virtual_users_on_virtual_domain_id" 59 | end 60 | 61 | create_view "user_aliases_view", "select concat(`virtual_user_aliases`.`name`,'@',`virtual_domains`.`name`) AS `source`,concat(`virtual_users`.`name`,'@',`virtual_domains`.`name`) AS `destination` from `virtual_user_aliases` join `virtual_users` join `virtual_domains` where ((`virtual_users`.`virtual_domain_id` = `virtual_domains`.`id`) and (`virtual_user_aliases`.`virtual_user_id` = `virtual_users`.`id`))", :force => true 62 | create_view "users_view", "select concat(`virtual_users`.`name`,'@',`virtual_domains`.`name`) AS `email`,`virtual_users`.`password` AS `password`,`virtual_users`.`quota` AS `quota` from `virtual_users` join `virtual_domains` where (`virtual_users`.`virtual_domain_id` = `virtual_domains`.`id`)", :force => true 63 | create_table "virtual_transports", :force => true do |t| 64 | t.string "name" 65 | t.string "destination" 66 | t.datetime "created_at", :null => false 67 | t.datetime "updated_at", :null => false 68 | t.index ["name"], :name => "index_virtual_transports_on_name" 69 | end 70 | 71 | end 72 | -------------------------------------------------------------------------------- /log/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/posty/posty_api/c399c2a87b7fb8739b5d162857a5ee697bfa067e/log/.gitkeep -------------------------------------------------------------------------------- /spec/api/v1_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Posty::API do 4 | include Rack::Test::Methods 5 | 6 | def app 7 | Posty::API 8 | end 9 | 10 | ApiKey.create unless ApiKey.active.any? 11 | 12 | before(:each) do 13 | header 'AUTH_TOKEN', ApiKey.active.first.access_token 14 | end 15 | 16 | shared_examples 'transports' do 17 | describe 'GET /api/v1/transports' do 18 | it 'returns all transports' do 19 | get '/api/v1/transports' 20 | expect(last_response.status).to eq(200) 21 | expect(JSON.parse(last_response.body)).to eq([]) 22 | end 23 | end 24 | 25 | describe "POST /api/v1/transports name='test.de' destination='smtp:[localhost]'" do 26 | it 'creates the transport test.de' do 27 | post '/api/v1/transports', 'name' => 'test.de', 'destination' => 'smtp:[localhost]' 28 | expect(last_response.status).to eq(201) 29 | expect(JSON.parse(last_response.body)['virtual_transport']).to include('name' => 'test.de') 30 | end 31 | end 32 | 33 | describe "PUT /api/v1/transports/test.de name='example.co.uk'" do 34 | it 'changes the transport name from test.de to example.co.uk' do 35 | put '/api/v1/transports/test.de', 'name' => 'example.co.uk' 36 | expect(last_response.status).to eq(200) 37 | expect(JSON.parse(last_response.body)['virtual_transport']).to include('name' => 'example.co.uk') 38 | end 39 | end 40 | 41 | describe 'DELETE /api/v1/transports/example.co.uk' do 42 | it 'delete the transport example.co.uk' do 43 | delete '/api/v1/transports/example.co.uk' 44 | expect(last_response.status).to eq(200) 45 | expect(JSON.parse(last_response.body)['virtual_transport']).to include('name' => 'example.co.uk') 46 | end 47 | end 48 | end 49 | 50 | shared_examples 'users' do 51 | describe 'GET /api/v1/domains/test.de/users' do 52 | it 'returns all users for the domain test.de' do 53 | get '/api/v1/domains/test.de/users' 54 | expect(last_response.status).to eq(200) 55 | expect(JSON.parse(last_response.body)).to eq([]) 56 | end 57 | end 58 | 59 | describe "POST /api/v1/domains/test.de/users name='test@test.de' password='tester', quota='1000000'" do 60 | it 'creates the user test@test.de' do 61 | post '/api/v1/domains/test.de/users', 'name' => 'test', 'password' => 'tester', 'quota' => 1_000_000 62 | expect(last_response.status).to eq(201) 63 | expect(JSON.parse(last_response.body)['virtual_user']).to include('name' => 'test') 64 | end 65 | end 66 | 67 | describe "PUT /api/v1/domains/test.de/users/test name='posty@test.de'" do 68 | it 'changes the user name from test@test.de to posty@test.de' do 69 | put '/api/v1/domains/test.de/users/test', 'name' => 'posty' 70 | expect(last_response.status).to eq(200) 71 | expect(JSON.parse(last_response.body)['virtual_user']).to include('name' => 'posty') 72 | end 73 | end 74 | 75 | describe 'DELETE /api/v1/domains/test.de/users/posty' do 76 | it 'delete the user posty@test.de' do 77 | delete '/api/v1/domains/test.de/users/posty' 78 | expect(last_response.status).to eq(200) 79 | expect(JSON.parse(last_response.body)['virtual_user']).to include('name' => 'posty') 80 | end 81 | end 82 | end 83 | 84 | shared_examples 'domain_aliases' do 85 | describe 'GET /api/v1/domains/test.de/aliases' do 86 | it 'returns all domain aliases for the domain test.de' do 87 | get '/api/v1/domains/test.de/aliases' 88 | expect(last_response.status).to eq(200) 89 | expect(JSON.parse(last_response.body)).to eq([]) 90 | end 91 | end 92 | 93 | describe "POST /api/v1/domains/test.de/aliases name='tester.de'" do 94 | it 'creates the domain alias tester.de' do 95 | post '/api/v1/domains/test.de/aliases', 'name' => 'tester.de' 96 | expect(last_response.status).to eq(201) 97 | expect(JSON.parse(last_response.body)['virtual_domain_alias']).to include('name' => 'tester.de') 98 | end 99 | end 100 | 101 | describe "PUT /api/v1/domains/test.de/aliases/tester.de name='tester2.de'" do 102 | it 'changes the domain alias name from tester.de to tester2.de' do 103 | put '/api/v1/domains/test.de/aliases/tester.de', 'name' => 'tester2.de' 104 | expect(last_response.status).to eq(200) 105 | expect(JSON.parse(last_response.body)['virtual_domain_alias']).to include('name' => 'tester2.de') 106 | end 107 | end 108 | 109 | describe 'DELETE /api/v1/domains/test.de/aliases/tester2.de' do 110 | it 'delete the domain alias tester2.de' do 111 | delete '/api/v1/domains/test.de/aliases/tester2.de' 112 | expect(last_response.status).to eq(200) 113 | expect(JSON.parse(last_response.body)['virtual_domain_alias']).to include('name' => 'tester2.de') 114 | end 115 | end 116 | end 117 | 118 | shared_examples 'user_aliases' do 119 | describe "POST /api/v1/domains/test.de/users name='destination@test.de' password='tester' quota=10000" do 120 | it 'creates the user destination@test.de' do 121 | post '/api/v1/domains/test.de/users', 'name' => 'destination', 'password' => 'tester', 'quota' => 10_000 122 | expect(last_response.status).to eq(201) 123 | expect(JSON.parse(last_response.body)['virtual_user']).to include('name' => 'destination') 124 | end 125 | end 126 | 127 | describe 'GET /api/v1/domains/test.de/users/destination/aliases' do 128 | it 'returns all aliases for the user destination@test.de' do 129 | get '/api/v1/domains/test.de/users/destination/aliases' 130 | expect(last_response.status).to eq(200) 131 | expect(JSON.parse(last_response.body)).to eq([]) 132 | end 133 | end 134 | 135 | describe "POST /api/v1/domains/test.de/users/destination/aliases name='newalias'" do 136 | it 'creates the user alias newalias@test.de' do 137 | post '/api/v1/domains/test.de/users/destination/aliases', 'name' => 'newalias' 138 | expect(last_response.status).to eq(201) 139 | expect(JSON.parse(last_response.body)['virtual_user_alias']).to include('name' => 'newalias') 140 | end 141 | end 142 | 143 | describe "PUT /api/v1/domains/test.de/users/destination/aliases/newalias name='newalias'" do 144 | it 'changes the user alias name from newalias@test.de to newalias2@test.de' do 145 | put '/api/v1/domains/test.de/users/destination/aliases/newalias', 'name' => 'newalias2' 146 | expect(last_response.status).to eq(200) 147 | expect(JSON.parse(last_response.body)['virtual_user_alias']).to include('name' => 'newalias2') 148 | end 149 | end 150 | 151 | describe 'DELETE /api/v1/domains/test.de/users/destination/aliases/newalias2' do 152 | it 'delete the user alias newalias2@test.de' do 153 | delete '/api/v1/domains/test.de/users/destination/aliases/newalias2' 154 | expect(last_response.status).to eq(200) 155 | expect(JSON.parse(last_response.body)['virtual_user_alias']).to include('name' => 'newalias2') 156 | end 157 | end 158 | end 159 | 160 | describe Posty::API do 161 | describe 'GET /api/v1/domains' do 162 | it 'returns all domains' do 163 | get '/api/v1/domains' 164 | expect(last_response.status).to eq(200) 165 | expect(JSON.parse(last_response.body)).to eq([]) 166 | end 167 | end 168 | 169 | describe "POST /api/v1/domains name='test.de'" do 170 | it 'creates the domain test.de' do 171 | post '/api/v1/domains', 'name' => 'test.de' 172 | expect(last_response.status).to eq(201) 173 | expect(JSON.parse(last_response.body)['virtual_domain']).to include('name' => 'test.de') 174 | end 175 | end 176 | 177 | include_examples 'users' 178 | include_examples 'domain_aliases' 179 | include_examples 'user_aliases' 180 | include_examples 'transports' 181 | 182 | describe "POST /api/v1/domains name='test.de'" do 183 | it 'creates the domain test.de' do 184 | post '/api/v1/domains', 'name' => 'test.de' 185 | expect(last_response.status).to eq(400) 186 | expect(JSON.parse(last_response.body)['error']).to include('name' => ['has already been taken']) 187 | end 188 | end 189 | 190 | describe "PUT /api/v1/domains/test.de name='posty-soft.de'" do 191 | it 'changes the domain name from test.de to posty-soft.de' do 192 | put '/api/v1/domains/test.de', 'name' => 'posty-soft.de' 193 | expect(last_response.status).to eq(200) 194 | expect(JSON.parse(last_response.body)['virtual_domain']).to include('name' => 'posty-soft.de') 195 | end 196 | end 197 | 198 | describe 'DELETE /api/v1/domains/posty-soft.de' do 199 | it 'delete the domain posty-soft.de' do 200 | delete '/api/v1/domains/posty-soft.de' 201 | expect(last_response.status).to eq(200) 202 | expect(JSON.parse(last_response.body)['virtual_domain']).to include('name' => 'posty-soft.de') 203 | end 204 | end 205 | end 206 | end 207 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RACK_ENV'] ||= 'test' 2 | 3 | require File.expand_path('../../config/environment', __FILE__) 4 | 5 | RSpec.configure do |config| 6 | config.mock_with :rspec 7 | config.expect_with :rspec 8 | end 9 | -------------------------------------------------------------------------------- /vendor/config/postfix/samples/mysql-virtual-domain-aliases.cf: -------------------------------------------------------------------------------- 1 | user = mysql_user 2 | password = mysql_password 3 | hosts = 127.0.0.1 4 | dbname = database_name 5 | query = SELECT destination FROM domain_aliases_view WHERE source='%s' 6 | -------------------------------------------------------------------------------- /vendor/config/postfix/samples/mysql-virtual-mailbox-domains.cf: -------------------------------------------------------------------------------- 1 | user = mysql_user 2 | password = mysql_password 3 | hosts = 127.0.0.1 4 | dbname = database_name 5 | query = SELECT 1 FROM virtual_domains WHERE virtual_domains.name='%s' 6 | -------------------------------------------------------------------------------- /vendor/config/postfix/samples/mysql-virtual-mailbox-maps.cf: -------------------------------------------------------------------------------- 1 | user = mysql_user 2 | password = mysql_password 3 | hosts = 127.0.0.1 4 | dbname = database_name 5 | query = SELECT 1 FROM users_view WHERE email='%s' 6 | -------------------------------------------------------------------------------- /vendor/config/postfix/samples/mysql-virtual-transports.cf: -------------------------------------------------------------------------------- 1 | user = mysql_user 2 | password = mysql_password 3 | hosts = 127.0.0.1 4 | dbname = database_name 5 | query = SELECT destination FROM virtual_transports WHERE name='%s' 6 | -------------------------------------------------------------------------------- /vendor/config/postfix/samples/mysql-virtual-user-aliases.cf: -------------------------------------------------------------------------------- 1 | user = mysql_user 2 | password = mysql_password 3 | hosts = 127.0.0.1 4 | dbname = database_name 5 | query = SELECT destination FROM user_aliases_view WHERE source='%s' 6 | --------------------------------------------------------------------------------