Archie  Clayton

Archie Clayton

1559628013

Sessionless Authentication using JWTs

Learn the intricate theory and practice of sessionless authentication using JWTs (with Node + Express + Passport JS) along with best practices

Authentication using stateful user sessions and session_ids stored in the cookie has been a strategy that has worked for decades. But with the rise of service oriented architectures and web services, there has been a push to design applications with the principle of statelessness in mind.

JWTs provide a *stateless *solution to **authentication **by removing the need to track session data on the server. Instead, JWTs allow us to safely and securely store our session data directly on the client in the form of a JWT.

A JWT is essentially a session data payload packaged in JSON and signed by the server

**JWTs **get a lot of criticism and skepticism, but the fact of the matter is that both session and JWT authentication have seen plenty of production usage and both implementations are secure and robust when it comes to handling user authentication. If statelessness is a practice you value in your system architecture, then JWTs are right for you. In this article, we will go over what JWTs are, the trade offs you make in choosing to use JWTs, and how you can implement them securely in your architecture.

How Authentication works

Before we begin, we need to agree what an authentication pipeline looks like:

  1. User POSTs to our server authentication details (over HTTPS):⠀⠀⠀⠀⠀⠀⠀ { username, password }
  2. The server determines whether the user is who she claims to be
  3. If the user’s *authentication *attempt succeeds, then our server sends some form of data (a token or a session id conventionally) that can be appended to every subsequent request which identifies the user as *authenticated *or not.

With sessionless auth, the data payload the client receives is our JWT, which should contain an encoded user identifier in JSON format signed by our back-end server. We put the *JWT *into our cookie so that we don’t have to store it in local-storage and risk XSS attacks. This is what an authentication process for a user named TheLegend27 might look like using JWTs:

A cookie is a special header that will be sent along with every subsequent request. It also conveniently persists across user sessions. This means that once TheLegend27 has logged in, her *JWT *will be sent along with every subsequent request she makes. All we have to do to verify her identity is to check the request cookie and verify the JWT.

Some important things to note:

  • We don’t keep track of user sessions on the server! 🙌 This is the big difference between *JWT *auth and *auth *using sessions. We have one less data source to worry about in our architecture with sessionless auth.
  • Our auth pipeline is super simple! If you’re just trying to implement authentication into your web app as intuitively and quickly as possible, then *JWTs *are the way to go.

So that’s the theory behind sessionless authentication using JWTs. Now if you have familiarity with *authentication *using sessions, this pipeline might look somewhat familiar. A JWT looks very similar to a HS256 encrypted session_id stored in the cookie. In fact, *JWTs *by default are signed using HS256! The difference between the two is that a JWT encodes all session data in its payload, while a session_id references a session from a sessions table.

JWTs remove the need keep track of sessions on the back-end. Instead, session data is encoded in the JWT payload. The trade off being made here is that the size of a JWT scales proportionally to the size of its payload. Luckily, a payload that takes the shape of {user_id, expiration_date } is plenty enough for most cases.

So that’s the theory. Lets get on to the practice!

Before discussing implementation, let’s discuss best practices in order to protect ourselves against the most common kinds of attacks / vulnerabilities when it comes to authentication:

  • XSS and SQL / noSQL injection attacks
  • Brute-forcing of user credentials attacks
  • An attacker getting a hold of a user’s JWT / cookie
  • An attacker getting a copy of or read credentials to our database

JWTs and best practices can protect us against all of these attacks. Let’s see how:

XSS attacks

This kind of attack is the simplest attack to protect ourselves against. A naive way to protect ourselves against XSS and code injection is to sanitize user input by doing the something like _.escape(<em>userInput</em>). But the issue with this solution is that when it comes to private data, it’s naive to blindly trust libraries to properly sanitize user input against sql xss attacks. Input sanitization is a great first layer of defense, but isn’t enough by itself.

Some more sturdy ways we can protect our user’s sensitive data is to use an ORM / ODM, which enforces parameterized queries. Or we could use Stored Procedures if we’re using SQL, which defines the query procedure at the database level as opposed to the code level.

If XSS and query sanitization best practices interest you, I highly recommend this resource by the Open Web Application Security Project Foundation on best practices to preventing XSS injection attacks.

Bruteforce User credential attacks

There are two ways an attacker will brute force user credentials:

A) They’ll attack a single user and try permutations of passwords until they hit a match.

B) They’ll attack a multitude of users and use a list of the most commonly used passwords to shallowly brute force until they find a hit. Here’s an excellent example of this: https://hackernoon.com/picking-the-low-hanging-passwords-b64684fe2c7

We can’t protect our users much from attack B. If a user sets their password to p@ssw0rd, then there’s not much we can do besides enforce stricter password policies in the future.

It turns out we can protect ourselves very well from attack A. The key is in making login requests take a non-trivial amount of time to process. An attacker can’t brute-force a user’s credentials if it takes 10¹¹ permutations to crack a 8 character password when each permutation takes 500ms to compute. We can make authentication take a non-trivial amount of time using a library called Bcrypt, which we’ll cover later.

Compromised JWT

This is the worst possible attack we can come across because it’s the hardest to resolve. Luckily, JWTs should rarely become compromised as we’re storing the JWT as a cookie and using HTTPS for all web transactions. Since we’re never storing the JWT in LocalStorage and only ever in the cookie, malicious attackers will not be able to steal our user’s JWT using XSS.

If an attacker somehow manages to steal a user’s JWT, then there’s unfortunately not much that can really be done. To minimize damages, you should design your application to require reauthentication before performing any high profile transaction such as a purchase or the changing of a password. And your JWTs should also have an expiration date. That way a compromised JWT will only work for so long.

This is what appears when you open the developer console on Facebook.com. This is a great way of preventing self-xss

Compromised Database

It turns out there are things we can do to protect user data and keep it obfuscated even if a hacker gets a hold of our database read credentials.

If we have a password, we don’t want to store it as plain-text in our database. Instead, we can salt and hash the password and store the salt and hash instead of our plain-text password.

Imagine we have a password p@ssw0rd. A salt is a random string of characters that we append to that password 'p@ssw0rd' + 'asdf253$n5', which we then pass through a hashing algorithm: SHA256('p@ssw0rd' + 'asdf253$n5'). We then store the salt and the hashed value in our user table.

An attacker can’t compute a user’s password with just a salt and hash.

This protects our user’s passwords pretty well if our database becomes compromised. You’ll still have to take action by for example requesting all users reset their passwords, but this will buy you plenty of time to do so.

It turns out there’s a standardized way of salting and hashing your password in a way that doesn’t require us to have a salt and hash field in our user table. The solution is called Bcrypt.

Bcrypt

Bcrypt is a password hashing algorithm that’s been around since 1999. It standardizes the salting and hashing of passwords. It also protects passwords from being brute-forced by making the process of authentication computationally intensive and “slow as hell.” We’ll be using this in our authentication implementation.

This is what a password passed through Bcrypt looks like. It contains the hashing algorithm version, hash cost, salt value and hashed password value.

The higher the hash cost, the more computational power it takes to authenticate

Now that we have all this in mind, let’s get to implementing authentication.

I’m going to be using MongoDB but feel free to use any database of choice. Nothing crazy here. This is just an ordinary User Schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  username: {
    type: String,
    index: true,
    unique: true,
    dropDups: true,
    required: true,
  },
  passwordHash: { //salted and hashed using bcrypt
    type: String,
    required: true,
  },
});

const User = mongoose.model('User', userSchema);
module.exports = User;

Next, we’re going to register two Passport strategies. We’re going to set up a Local Strategy and a JWT Strategy. In the future, when we call passport.authenticate(<em>'local'</em>) or passport.authenticate(<em>'jwt'</em>), it’s going to invoke these respective middlewares.

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const passportJWT = require('passport-jwt');
const JWTStrategy = passportJWT.Strategy;
const bcrypt = require('bcrypt');

const { secret } = require('./keys');

const UserModel = require('./models/user');

passport.use(new LocalStrategy({
  usernameField: username,
  passwordField: password,
}, async (username, password, done) => {
  try {
    const userDocument = await UserModel.findOne({username: username}).exec();
    const passwordsMatch = await bcrypt.compare(password, userDocument.passwordHash);

    if (passwordsMatch) {
      return done(null, userDocument);
    } else {
      return done('Incorrect Username / Password');
    }
  } catch (error) {
    done(error);
  }
}));

passport.use(new JWTStrategy({
    jwtFromRequest: req => req.cookies.jwt,
    secretOrKey: secret,
  },
  (jwtPayload, done) => {
    if (Date.now() > jwtPayload.expires) {
      return done('jwt expired');
    }

    return done(null, jwtPayload);
  }
));

The Local strategy extracts the username and password from req.body and verifies the user by verifying it against the User table.

The JWT strategy extracts the JWT from the cookie, and uses the application’s secret to verify its signature:

The signature is dependent on the payload. If a user tampers with and changes the payload, then the signature changes as well

Now, last but not least, we define our /login and /register routes:

const express = require('express');
const passport = require('passport');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const keys = require('../keys');
const UserModel = require('../models/user');

const router = express.Router();

router.post('/register', async (req, res) => {
  const { username, password } = req.body;

  // authentication will take approximately 13 seconds
  // https://pthree.org/wp-content/uploads/2016/06/bcrypt.png
  const hashCost = 10;

  try {
    const passwordHash = await bcrypt.hash(password, hashCost);
    const userDocument = new UserModel({ username, passwordHash });
    await userDocument.save();
    
    res.status(200).send({ username });
    
  } catch (error) {
    res.status(400).send({
      error: 'req body should take the form { username, password }',
    });
  }
});

router.post('/login', (req, res) => {
  passport.authenticate(
    'local',
    { session: false },
    (error, user) => {

      if (error || !user) {
        res.status(400).json({ error });
      }

      /** This is what ends up in our JWT */
      const payload = {
        username: user.username,
        expires: Date.now() + parseInt(process.env.JWT_EXPIRATION_MS),
      };

      /** assigns payload to req.user */
      req.login(payload, {session: false}, (error) => {
        if (error) {
          res.status(400).send({ error });
        }

        /** generate a signed json web token and return it in the response */
        const token = jwt.sign(JSON.stringify(payload), keys.secret);

        /** assign our jwt to the cookie */
        res.cookie('jwt', jwt, { httpOnly: true, secure: true });
        res.status(200).send({ username });
      });
    },
  )(req, res);
});

module.exports = router;

/register is pretty straight forward. We’re creating a new User and saving it to our Users table and responding with status 200 if we succeed.

/login is a bit more complicated. A break down of what’s going on: We’re authenticating with the local strategy. If authentication succeeds, we compose a payload for our JWT, and call req.login, which assigns the payload to req.user. We then compose our JWT by callingjwt.sign, and then we set our JWT to our cookie.

Now, if we need to create a route that requires authentication, we can use our JWT middleware to check if the user is authenticated!

router.get('/protected',
  passport.authenticate('jwt', {session: false}),
  (req, res) => {
    const { user } = req;

    res.status(200).send({ user });
  });

Conclusion

That’s it! There’s a whole rabbit-hole awaiting those who are interested in security and authentication. I’ve personally been stuck in this rabbit hole for far longer than I care to admit.

This article is the culmination of my research into best practices with JWTs and it should be enough to get your feet wet with sessionless auth. JWTs are an elegant solution to authentication and I hope this article has shed some light on how they work and how you can implement them yourself securely.

#javascript #node-js #express #security #web-development

What is GEEK

Buddha Community

Sessionless Authentication using JWTs

How To Set Up Two-Factor Authentication in cPanel

What is 2FA
Two-Factor Authentication (or 2FA as it often referred to) is an extra layer of security that is used to provide users an additional level of protection when securing access to an account.
Employing a 2FA mechanism is a vast improvement in security over the Singe-Factor Authentication method of simply employing a username and password. Using this method, accounts that have 2FA enabled, require the user to enter a one-time passcode that is generated by an external application. The 2FA passcode (usually a six-digit number) is required to be input into the passcode field before access is granted. The 2FA input is usually required directly after the username and password are entered by the client.

#tutorials #2fa #access #account security #authentication #authentication method #authentication token #cli #command line #cpanel #feature manager #google authenticator #one time password #otp #otp authentication #passcode #password #passwords #qr code #security #security code #security policy #security practices #single factor authentication #time-based one-time password #totp #two factor authentication #whm

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

I am Developer

1602036957

Laravel 8 REST API Authentication with Passport Example Tutorial

Laravel 8 rest api authentication with passport tutorial, you will learn step by step how to create rest API with laravel 8 passport authentication. And as well as how to install and cofigure passport auth in laravel 8 app.

Laravel 8 API Authentication with Passport Tutorial

Step 1: Download Laravel 8 App
Step 2: Database Configuration
Step 3: Install Passport Auth
Step 4: Passport Configuration
Step 5: Run Migration
Step 6: Create APIs Route
Step 7: Create Passport Auth Controller
Step 8: Now Test Laravel REST API in Postman

https://www.tutsmake.com/laravel-8-rest-api-authentication-with-passport/

#laravel api authentication with passport #laravel 8 api authentication #laravel 8 api authentication token tutorial #laravel 8 api authentication using passport #laravel 8 api authentication session

Nat  Grady

Nat Grady

1660108440

Wordcloud2: R interface to Wordcloud for Data Visualization

wordcloud2

R interface to wordcloud for data visualization. Timdream's wordcloud2.js is used in this package.

Original description

Installation

devtools::install_github("lchiffon/wordcloud2")

knitr and shiny is support in wordcloud2 package.

Example

library(wordcloud2)
wordcloud2(demoFreq, size = 1,shape = 'star')

1

wordcloud2(demoFreq, size = 2, minRotation = -pi/2, maxRotation = -pi/2)

1

wordcloud2(demoFreq, size = 2, minRotation = -pi/6, maxRotation = -pi/6,
  rotateRatio = 1)

1

Chinese version

## Sys.setlocale("LC_CTYPE","eng")
wordcloud2(demoFreqC, size = 2, fontFamily = "微软雅黑",
           color = "random-light", backgroundColor = "grey")

1

Example of successfully deploying interactivate clickable wordcloud with special shape on R-shiny

Thanks JacobXPX's contribution to this feature:

Thanks AdamSpannbauer for pointing out the issues.

Additional features are added or modified:

hover information display are fixed, refering AdeelK93's previous work, thanks!

multiple wordclouds which seperatedly click are supported.

clickedWordInputId is changed to be automatically generated by: paste0(outputId, "_clicked_word")).

See sample below for more details:

library(shiny)
library(wordcloud2)
shinyApp(
  ui=shinyUI(fluidPage(
    #using default clicked word input id
    wordcloud2Output("my_wc", width = "50%", height = "400px"),
    #using custom clicked word input id
    wordcloud2Output("my_wc2", width = "50%", height = "400px"),
    
    verbatimTextOutput("print"),
    verbatimTextOutput("print2")
  )),
  server=shinyServer(function(input,output,session){
    
    figPath = system.file("examples/a.png",package = "wordcloud2")
    
    output$my_wc  = renderWordcloud2(wordcloud2(data = demoFreq, figPath = figPath, size = 0.4,color = "blue"))
    output$my_wc2 = renderWordcloud2(wordcloud2(demoFreq))
    
    #using default clicked word input id
    output$print  = renderPrint(input$my_wc_clicked_word)
    #using custom clicked word input id
    output$print2 = renderPrint(input$my_wc2_clicked_word)
  })
)

run the above code and click refresh, it will work.

1

contributors

Download Details:

Author: Lchiffon
Source Code: https://github.com/Lchiffon/wordcloud2 

#r #datavisualization 

Josefa  Corwin

Josefa Corwin

1659736920

Mailboxer: A Rails Gem to Send Messages inside A Web Application

Mailboxer

This project is based on the need for a private message system for ging / social_stream. Instead of creating our core message system heavily dependent on our development, we are trying to implement a generic and potent messaging gem.

After looking for a good gem to use we noticed the lack of messaging gems and functionality in them. Mailboxer tries to fill this void delivering a powerful and flexible message system. It supports the use of conversations with two or more participants, sending notifications to recipients (intended to be used as system notifications “Your picture has new comments”, “John Doe has updated his document”, etc.), and emailing the messageable model (if configured to do so). It has a complete implementation of a Mailbox object for each messageable with inbox, sentbox and trash.

The gem is constantly growing and improving its functionality. As it is used with our parallel development ging / social_stream we are finding and fixing bugs continously. If you want some functionality not supported yet or marked as TODO, you can create an issue to ask for it. It will be great feedback for us, and we will know what you may find useful in the gem.

Mailboxer was born from the great, but outdated, code from lpsergi / acts_as_messageable.

We are now working to make exhaustive documentation and some wiki pages in order to make it even easier to use the gem to its full potential. Please, give us some time if you find something missing or ask for it. You can also find us on the Gitter room for this repo. Join us there to talk.

Installation

Add to your Gemfile:

gem 'mailboxer'

Then run:

$ bundle install

Run install script:

$ rails g mailboxer:install

And don't forget to migrate your database:

$ rake db:migrate

You can also generate email views:

$ rails g mailboxer:views

Upgrading

If upgrading from 0.11.0 to 0.12.0, run the following generators:

$ rails generate mailboxer:namespacing_compatibility
$ rails generate mailboxer:install -s

Then, migrate your database:

$ rake db:migrate

Requirements & Settings

Emails

We are now adding support for sending emails when a Notification or a Message is sent to one or more recipients. You should modify the mailboxer initializer (/config/initializer/mailboxer.rb) to edit these settings:

Mailboxer.setup do |config|
  #Enables or disables email sending for Notifications and Messages
  config.uses_emails = true
  #Configures the default `from` address for the email sent for Messages and Notifications of Mailboxer
  config.default_from = "no-reply@dit.upm.es"
  ...
end

You can change the way in which emails are delivered by specifying a custom implementation of notification and message mailers:

Mailboxer.setup do |config|
  config.notification_mailer = CustomNotificationMailer
  config.message_mailer = CustomMessageMailer
  ...
end

If you have subclassed the Mailboxer::Notification class, you can specify the mailers using a member method:

class NewDocumentNotification < Mailboxer::Notification
  def mailer_class
    NewDocumentNotificationMailer
  end
end

class NewCommentNotification < Mailboxer::Notification
  def mailer_class
    NewDocumentNotificationMailer
  end
end

Otherwise, the mailer class will be determined by appending 'Mailer' to the mailable class name.

User identities

Users must have an identity defined by a name and an email. We must ensure that Messageable models have some specific methods. These methods are:

#Returning any kind of identification you want for the model
def name
  return "You should add method :name in your Messageable model"
end
#Returning the email address of the model if an email should be sent for this object (Message or Notification).
#If no mail has to be sent, return nil.
def mailboxer_email(object)
  #Check if an email should be sent for that object
  #if true
  return "define_email@on_your.model"
  #if false
  #return nil
end

These names are explicit enough to avoid colliding with other methods, but as long as you need to change them you can do it by using mailboxer initializer (/config/initializer/mailboxer.rb). Just add or uncomment the following lines:

Mailboxer.setup do |config|
  # ...
  #Configures the methods needed by mailboxer
  config.email_method = :mailboxer_email
  config.name_method = :name
  config.notify_method = :notify
  # ...
end

You may change whatever you want or need. For example:

config.email_method = :notification_email
config.name_method = :display_name
config.notify_method = :notify_mailboxer

Will use the method notification_email(object) instead of mailboxer_email(object), display_name for name and notify_mailboxer for notify.

Using default or custom method names, if your model doesn't implement them, Mailboxer will use dummy methods so as to notify you of missing methods rather than crashing.

Preparing your models

In your model:

class User < ActiveRecord::Base
  acts_as_messageable
end

You are not limited to the User model. You can use Mailboxer in any other model and use it in several different models. If you have ducks and cylons in your application and you want to exchange messages as if they were the same, just add acts_as_messageable to each one and you will be able to send duck-duck, duck-cylon, cylon-duck and cylon-cylon messages. Of course, you can extend it for as many classes as you need.

Example:

class Duck < ActiveRecord::Base
  acts_as_messageable
end
class Cylon < ActiveRecord::Base
  acts_as_messageable
end

Mailboxer API

Warning for version 0.8.0

Version 0.8.0 sees Messageable#read and Messageable#unread renamed to mark_as_(un)read, and Receipt#read and Receipt#unread to is_(un)read. This may break existing applications, but read is a reserved name for Active Record, and the best pratice in this case is simply avoid using it.

How can I send a message?

#alfa wants to send a message to beta
alfa.send_message(beta, "Body", "subject")

How can I read the messages of a conversation?

As a messageable, what you receive are receipts, which are associated with the message itself. You should retrieve your receipts for the conversation and get the message associated with them.

This is done this way because receipts save the information about the relation between messageable and the messages: is it read?, is it trashed?, etc.

#alfa gets the last conversation (chronologically, the first in the inbox)
conversation = alfa.mailbox.inbox.first

#alfa gets it receipts chronologically ordered.
receipts = conversation.receipts_for alfa

#using the receipts (i.e. in the view)
receipts.each do |receipt|
  ...
  message = receipt.message
  read = receipt.is_unread? #or message.is_unread?(alfa)
  ...
end

How can I reply to a message?

#alfa wants to reply to all in a conversation
#using a receipt
alfa.reply_to_all(receipt, "Reply body")

#using a conversation
alfa.reply_to_conversation(conversation, "Reply body")
#alfa wants to reply to the sender of a message (and ONLY the sender)
#using a receipt
alfa.reply_to_sender(receipt, "Reply body")

How can I delete a message from trash?

#delete conversations forever for one receipt (still in database)
receipt.mark_as_deleted

#you can mark conversation as deleted for one participant
conversation.mark_as_deleted participant

#Mark the object as deleted for messageable
#Object can be:
  #* A Receipt
  #* A Conversation
  #* A Notification
  #* A Message
  #* An array with any of them
alfa.mark_as_deleted conversation

# get available message for specific user
conversation.messages_for(alfa)

How can I retrieve my conversations?

#alfa wants to retrieve all his conversations
alfa.mailbox.conversations

#A wants to retrieve his inbox
alfa.mailbox.inbox

#A wants to retrieve his sent conversations
alfa.mailbox.sentbox

#alfa wants to retrieve his trashed conversations
alfa.mailbox.trash

How can I paginate conversations?

You can use Kaminari to paginate the conversations as normal. Please, make sure you use the last version as mailboxer uses select('DISTINCT conversations.*') which was not respected before Kaminari 0.12.4 according to its changelog. Working correctly on Kaminari 0.13.0.

#Paginating all conversations using :page parameter and 9 per page
conversations = alfa.mailbox.conversations.page(params[:page]).per(9)

#Paginating received conversations using :page parameter and 9 per page
conversations = alfa.mailbox.inbox.page(params[:page]).per(9)

#Paginating sent conversations using :page parameter and 9 per page
conversations = alfa.mailbox.sentbox.page(params[:page]).per(9)

#Paginating trashed conversations using :page parameter and 9 per page
conversations = alfa.mailbox.trash.page(params[:page]).per(9)

You can take a look at the full documentation for Mailboxer in rubydoc.info.

Do you want to test Mailboxer?

Thanks to Roman Kushnir (@RKushnir) you can test Mailboxer with this sample app.

I need a GUI!

If you need a GUI you should take a look at these links:

Contributors


Author: mailboxer
Source code: https://github.com/mailboxer/mailboxer
License: MIT license

#ruby  #ruby-on-rails