Plugin Directory

Changeset 2862545


Ignore:
Timestamp:
02/09/2023 10:26:34 AM (3 years ago)
Author:
cudedesign
Message:

Plugin update 1.1.0

Location:
wordthree
Files:
180 added
5 deleted
24 edited

Legend:

Unmodified
Added
Removed
  • wordthree/trunk/assets/css/admin.css

    r2793538 r2862545  
    8787}
    8888
     89.copy-shortcode-btn img {
     90    max-width: 15px;
     91    padding-top: 15px;
     92}
  • wordthree/trunk/assets/js/metamask-login.js

    r2793538 r2862545  
    1 class WordThreeMetamask {
    2     constructor() {
    3         this.confirmBox = new WordThreePopUpModal();
    4         this.apiUrl = wordthree.apiUrl;
    5         this.metamaskLoginButton = document.querySelector('.wordthree-metamask-login');
    6         this.metamaskRegisterButton = document.querySelector('.wordthree-metamask-register');
    7         this.metamaskLinkButton = document.querySelector('.wordthree-metamask-link');
    8         this.metamaskUnlinkButton = document.querySelector('.wordthree-metamask-unlink');
    9     }
    10 
    11     fetch(url, data = {}) {
    12         return fetch(url, {
    13             method: 'POST',
    14             headers: {
    15                 "Content-Type": "application/json",
    16                 "X-WP-Nonce": wordthree.nonce
    17             },
    18             body: JSON.stringify(data)
    19         });
    20     }
    21 
    22     signTokenMessage() {
    23         return this.getAccount().then(publicAddress => {
    24             return this.getToken(publicAddress).then(response => {
    25                 return this.handleSignMessage(response.message, publicAddress).then(signature => {
    26                     return {publicAddress, signature};
    27                 });
    28             });
    29         });
    30     }
    31 
    32     async getAccount() {
    33         let accounts = await ethereum.request({method: 'eth_requestAccounts'});
    34         return accounts[0];
    35     }
    36 
    37     async getToken(address) {
    38         const tokenUrl = this.apiUrl + wordthree.tokenUrl;
    39         let response = await this.fetch(tokenUrl, {address});
    40 
    41         if (!response.ok) {
    42             throw Error(response.statusText);
    43         }
    44         return response.json();
    45     }
    46 
    47     async handleSignMessage(message, publicAddress) {
    48         return await ethereum.request({method: "personal_sign", params: [publicAddress, message]});
    49     }
    50 
    51     async handleLogin(publicAddress, signature) {
    52         const loginUrl = this.apiUrl + wordthree.loginUrl;
    53         let response = await this.fetch(loginUrl, {address: publicAddress, signature: signature});
    54         if (!response.ok) {
    55             throw Error(response.statusText);
    56         }
    57         return response.json();
    58     }
    59 
    60     async handleRegister(publicAddress, signature) {
    61         const registerUrl = this.apiUrl + wordthree.registerUrl;
    62         let response = await this.fetch(registerUrl, {address: publicAddress, signature: signature});
    63         if (!response.ok) {
    64             throw Error(response.statusText);
    65         }
    66         return response.json();
    67     }
    68 
    69     async handleLinkAccount(publicAddress, signature) {
    70         const linkUrl = this.apiUrl + wordthree.linkUrl;
    71         let response = await this.fetch(linkUrl, {address: publicAddress, signature: signature});
    72         if (!response.ok) {
    73             throw Error(response.statusText);
    74         }
    75         return response.json();
    76     }
    77 
    78     async handleUnlink(publicAddress, signature) {
    79         const unlinkUrl = this.apiUrl + wordthree.unlinkUrl;
    80         let response = await this.fetch(unlinkUrl, {address: publicAddress, signature: signature});
    81         if (!response.ok) {
    82             throw Error(response.statusText);
    83         }
    84         return response.json();
    85     }
    86 
    87     loginUser() {
    88         this.signTokenMessage().then(r => {
    89             this.handleLogin(r.publicAddress, r.signature).then(response => {
    90                 if (response.success) {
    91                     window.location.href = this.metamaskLoginButton.dataset.redirectUrl ?? window.location.href;
    92                     return;
    93                 }
    94 
    95                 this.confirmBox.open({
    96                     message: response.message,
    97                     confirmButtonText: 'OK',
    98                     showCancelButton: false
    99                 });
    100             }).catch(error => this.confirmBox.open({
    101                 message: error.message,
    102                 confirmButtonText: 'OK',
    103                 showCancelButton: false
    104             }));
    105         }).catch(error => this.confirmBox.open({
    106             message: error.message,
    107             confirmButtonText: 'OK',
    108             showCancelButton: false
    109         }));
    110     }
    111 
    112     registerUser() {
    113         this.signTokenMessage().then(r => {
    114             this.handleRegister(r.publicAddress, r.signature).then(response => {
    115                 if (response.success) {
    116                     window.location.href = this.metamaskRegisterButton.dataset.redirectUrl ?? window.location.href;
    117                     return;
    118                 }
    119 
    120                 this.confirmBox.open({
    121                     message: response.message,
    122                     confirmButtonText: 'OK',
    123                     showCancelButton: false
    124                 });
    125             }).catch(error => this.confirmBox.open({
    126                 message: error.message,
    127                 confirmButtonText: 'OK',
    128                 showCancelButton: false
    129             }));
    130         }).catch(error => this.confirmBox.open({
    131             message: error.message,
    132             confirmButtonText: 'OK',
    133             showCancelButton: false
    134         }));
    135     }
    136 
    137     link() {
    138         this.signTokenMessage().then(r => {
    139             this.handleLinkAccount(r.publicAddress, r.signature).then(response => {
    140                 if (response.success) {
    141                     window.location.reload();
    142                     return;
    143                 }
    144 
    145                 this.confirmBox.open({
    146                     message: response.message,
    147                     confirmButtonText: 'OK',
    148                     showCancelButton: false
    149                 });
    150             }).catch(error => this.confirmBox.open({
    151                 message: error.message,
    152                 confirmButtonText: 'OK',
    153                 showCancelButton: false
    154             }));
    155         }).catch(error => this.confirmBox.open({
    156             message: error.message,
    157             confirmButtonText: 'OK',
    158             showCancelButton: false
    159         }));
    160     }
    161 
    162     unlink() {
    163         this.signTokenMessage().then(r => {
    164             this.handleUnlink(r.publicAddress, r.signature).then(response => {
    165                 if (response.success) {
    166                     window.location.reload();
    167                     return;
    168                 }
    169 
    170                 this.confirmBox.open({
    171                     message: response.message,
    172                     confirmButtonText: 'OK',
    173                     showCancelButton: false
    174                 });
    175             }).catch(error => this.confirmBox.open({
    176                 message: error.message,
    177                 confirmButtonText: 'OK',
    178                 showCancelButton: false
    179             }));
    180         }).catch(error => this.confirmBox.open({
    181             message: error.message,
    182             confirmButtonText: 'OK',
    183             showCancelButton: false
    184         }));
    185     }
    186 
    187     init() {
    188         this.initEvents();
    189     }
    190 
    191     initEvents() {
    192         this.createLoginEvent();
    193         this.createRegisterEvent();
    194         this.createUnlinkEvent();
    195         this.createLinkEvent();
    196     }
    197 
    198     createLoginEvent() {
    199         if (this.metamaskLoginButton) {
    200             this.metamaskLoginButton.addEventListener('click', async (e) => {
    201                 if (!this.checkMetamaskActive()) {
    202                     return;
    203                 }
    204 
    205                 this.loginUser();
    206             });
    207         }
    208     }
    209 
    210     createRegisterEvent() {
    211         if (this.metamaskRegisterButton) {
    212             this.metamaskRegisterButton.addEventListener('click', async (e) => {
    213                 if (!this.checkMetamaskActive()) {
    214                     return;
    215                 }
    216 
    217                 this.registerUser();
    218             });
    219         }
    220     }
    221 
    222     createLinkEvent() {
    223         if (this.metamaskLinkButton) {
    224             this.metamaskLinkButton.addEventListener('click', (e) => {
    225                 if (!this.checkMetamaskActive()) {
    226                     return;
    227                 }
    228 
    229                 this.link();
    230             });
    231         }
    232     }
    233 
    234     createUnlinkEvent() {
    235         if (this.metamaskUnlinkButton) {
    236             this.metamaskUnlinkButton.addEventListener('click', (e) => {
    237                 if (!this.checkMetamaskActive()) {
    238                     return;
    239                 }
    240 
    241                 this.unlink();
    242             });
    243         }
    244     }
    245 
    246     checkMetamaskActive() {
    247         if (!window.ethereum || !ethereum.isMetaMask) {
    248             this.confirmBox.open({
    249                 message: 'MetaMask browser extension should be installed in order to use the login.',
    250                 confirmButtonText: 'Install Now',
    251                 cancelButtonText: 'Cancel',
    252                 showCancelButton: true
    253             }, (confirm) => {
    254                 if (confirm) {
    255                     window.open('https://metamask.io', '_blank');
    256                 }
    257             });
    258 
    259             return false;
    260         }
    261 
    262         return true;
    263     }
     1/* global wordthree */
     2class WordThreeMetamaskLogin {
     3    constructor() {
     4        this.metamask                = new WordThreeMetamask();
     5        this.confirmBox              = new WordThreePopUpModal();
     6        this.apiUrl                  = wordthree.apiUrl;
     7        this.metamaskLoginButtons    = document.querySelectorAll('.wordthree-metamask-login');
     8        this.metamaskRegisterButtons = document.querySelectorAll('.wordthree-metamask-register');
     9        this.metamaskLinkButtons     = document.querySelectorAll('.wordthree-metamask-link');
     10        this.metamaskUnlinkButton    = document.querySelector('.wordthree-metamask-unlink');
     11        this.metamaskUnlinkButtons   = document.querySelectorAll('.wordthree-metamask-unlink');
     12    }
     13
     14    fetch(url, data = {}) {
     15        return fetch(url, {
     16            method: 'POST',
     17            headers: {
     18                "Content-Type": "application/json",
     19                "X-WP-Nonce": wordthree.nonce
     20            },
     21            body: JSON.stringify(data)
     22        });
     23    }
     24
     25    signTokenMessage() {
     26        return this.metamask.getAccount().then(publicAddress => {
     27            return this.getToken(publicAddress).then(response => {
     28                if (!response.success) {
     29                    throw Error(response.message);
     30                }
     31
     32                return this.metamask.handleSignMessagePersonal(response.message, publicAddress).then(signature => {
     33                    return {publicAddress, signature};
     34                });
     35            });
     36        });
     37    }
     38
     39    async getToken(address) {
     40        const tokenUrl = this.apiUrl + wordthree.restRoutes.tokenUrl;
     41        let response   = await this.fetch(tokenUrl, {address});
     42
     43        return response.json();
     44    }
     45
     46    async handleLogin(publicAddress, signature) {
     47        const loginUrl = this.apiUrl + wordthree.restRoutes.loginUrl;
     48        let response   = await this.fetch(loginUrl, {address: publicAddress, signature: signature});
     49
     50        return response.json();
     51    }
     52
     53    async handleRegister(publicAddress, signature) {
     54        const registerUrl = this.apiUrl + wordthree.restRoutes.registerUrl;
     55        let response      = await this.fetch(registerUrl, {address: publicAddress, signature: signature});
     56
     57        return response.json();
     58    }
     59
     60    async handleLinkAccount(publicAddress, signature) {
     61        const linkUrl = this.apiUrl + wordthree.restRoutes.linkUrl;
     62        let response  = await this.fetch(linkUrl, {address: publicAddress, signature: signature});
     63
     64        return response.json();
     65    }
     66
     67    async handleUnlink(publicAddress, signature) {
     68        const unlinkUrl = this.apiUrl + wordthree.restRoutes.unlinkUrl;
     69        let response    = await this.fetch(unlinkUrl, {address: publicAddress, signature: signature});
     70        /*if (!response.ok) {
     71            throw Error(response.statusText);
     72        }*/
     73        return response.json();
     74    }
     75
     76    loginUser() {
     77        return this.signTokenMessage().then(r => {
     78            return this.handleLogin(r.publicAddress, r.signature).then(response => {
     79                if (!response.success) {
     80                    throw Error(response.message);
     81                }
     82                return response.message;
     83            })
     84        });
     85    }
     86
     87    registerUser() {
     88        return this.signTokenMessage().then(r => {
     89            return this.handleRegister(r.publicAddress, r.signature).then(response => {
     90                if (!response.success) {
     91                    throw Error(response.message);
     92                }
     93                return response.message;
     94            })
     95        });
     96    }
     97
     98    link() {
     99        return this.signTokenMessage().then(r => {
     100            return this.handleLinkAccount(r.publicAddress, r.signature).then(response => {
     101                if (!response.success) {
     102                    throw Error(response.message);
     103                }
     104                return response.message;
     105            });
     106        });
     107    }
     108
     109    unlink() {
     110        return this.signTokenMessage().then(r => {
     111            return this.handleUnlink(r.publicAddress, r.signature).then(response => {
     112                if (!response.success) {
     113                    throw Error(response.message);
     114                }
     115
     116                return response.message;
     117            });
     118        });
     119    }
     120
     121    init() {
     122        this.initEvents();
     123    }
     124
     125    initEvents() {
     126        this.createLoginEvent();
     127        this.createRegisterEvent();
     128        this.createUnlinkEvent();
     129        this.createLinkEvent();
     130    }
     131
     132    createLoginEvent() {
     133        this.metamaskLoginButtons.forEach((button) => {
     134            button.addEventListener('click', async (e) => {
     135                if (!this.metamask.checkMetamaskActive()) {
     136                    this.showInstallMetamaskPopup();
     137                    return;
     138                }
     139
     140                this.loginUser().then(message => {
     141                    this.openConfirmBox(message, (confirm) => {
     142                        if (confirm) {
     143                            if (button.dataset.redirectUrl) {
     144                                location.href = button.dataset.redirectUrl;
     145                                return;
     146                            }
     147                            location.reload();
     148                        }
     149                    })
     150                }).catch(err => this.openConfirmBox(err.message));
     151            });
     152        });
     153    }
     154
     155    createRegisterEvent() {
     156        this.metamaskRegisterButtons.forEach((button) => {
     157            button.addEventListener('click', async (e) => {
     158                if (!this.metamask.checkMetamaskActive()) {
     159                    this.showInstallMetamaskPopup();
     160                    return;
     161                }
     162
     163                this.registerUser().then(message => {
     164                    this.openConfirmBox(message, (confirm) => {
     165                        if (confirm) {
     166                            if (button.dataset.redirectUrl) {
     167                                location.href = button.dataset.redirectUrl;
     168                                return;
     169                            }
     170                            location.reload();
     171                        }
     172                    });
     173                }).catch(err => this.openConfirmBox(err.message));
     174            });
     175        });
     176    }
     177
     178    createLinkEvent() {
     179        this.metamaskLinkButtons.forEach(button => {
     180            button.addEventListener('click', (e) => {
     181                if (!this.metamask.checkMetamaskActive()) {
     182                    this.showInstallMetamaskPopup();
     183                    return;
     184                }
     185
     186                this.link().then(message => {
     187                    this.openConfirmBox(message, (confirm) => {
     188                        if (confirm) {
     189                            location.reload();
     190                        }
     191                    });
     192                }).catch(err => this.openConfirmBox(err.message));
     193            });
     194        });
     195    }
     196
     197    createUnlinkEvent() {
     198        this.metamaskUnlinkButtons.forEach(button => {
     199            button.addEventListener('click', (e) => {
     200                if (!this.metamask.checkMetamaskActive()) {
     201                    this.showInstallMetamaskPopup();
     202                    return;
     203                }
     204
     205                this.unlink().then(message => {
     206                    this.openConfirmBox(message, (confirm) => {
     207                        if (confirm) {
     208                            location.reload();
     209                        }
     210                    });
     211                }).catch(err => this.openConfirmBox(err.message));
     212            });
     213        });
     214    }
     215
     216    openConfirmBox(message, callback) {
     217        this.confirmBox.open({
     218            message: message,
     219            confirmButtonText: wordthree.translations.ok.toUpperCase(),
     220            showCancelButton: false
     221        }, callback);
     222    };
     223
     224    showInstallMetamaskPopup() {
     225        this.confirmBox.open({
     226            message: wordthree.translations.metamask_required_login,
     227            confirmButtonText: wordthree.translations.install_now,
     228            cancelButtonText: wordthree.translations.cancel,
     229            showCancelButton: true
     230        }, (confirm) => {
     231            if (confirm) {
     232                window.open('https://metamask.io', '_blank');
     233            }
     234        });
     235    }
    264236}
    265237
    266238(function (d, w) {
    267     const metaMask = new WordThreeMetamask();
    268     metaMask.init();
     239    const metaMaskLogin = new WordThreeMetamaskLogin();
     240    metaMaskLogin.init();
    269241})(document, window);
  • wordthree/trunk/assets/js/popup-modal.js

    r2793538 r2862545  
    11class WordThreePopUpModal {
    2     constructor(params = {}) {
    3         let _this = this;
    4         this.selector = document.getElementById('wordthree-confirm-box');
    5         this.confirmButton = this.selector.querySelector('.btn-yes');
    6         this.cancelButton = this.selector.querySelector('.btn-cancel');
    7         this.messageField = this.selector.querySelector('.wt-message');
     2    constructor(params = {}) {
     3        let _this          = this;
     4        this.selector      = document.getElementById('wordthree-confirm-box');
     5        this.confirmButton = this.selector.querySelector('.btn-yes');
     6        this.cancelButton = this.selector.querySelector('.btn-cancel');
     7        this.messageField = this.selector.querySelector('.wt-message');
    88
    9         this.setConfirmBoxParams(params);
     9        this.setConfirmBoxParams(params);
    1010
    11         this.confirmButton.addEventListener('click', function (e) {
    12             _this.confirm();
    13         });
     11        this.confirmButton.addEventListener('click', function (e) {
     12            _this.confirm();
     13        });
    1414
    15         this.cancelButton.addEventListener('click', function (e) {
    16             _this.cancel();
    17         });
     15        this.cancelButton.addEventListener('click', function (e) {
     16            _this.cancel();
     17        });
    1818
    19         document.querySelector('.wordthree-confirm-overlay').addEventListener('click', function () {
    20             _this.close();
    21         });
    22     }
     19        document.querySelector('.wordthree-confirm-overlay').addEventListener('click', function () {
     20            _this.close();
     21        });
     22    }
    2323
    24     setConfirmBoxParams(params) {
    25         this.confirmButtonText = params.confirmButtonText ?? this.cancelButtonText ?? 'Yes';
    26         this.cancelButtonText = params.cancelButtonText ?? this.cancelButtonText ?? 'Cancel';
    27         this.message = params.message ?? '';
    28         this.setMessage();
    29         this.confirmButton.textContent = this.confirmButtonText;
    30         this.cancelButton.textContent = this.cancelButtonText;
    31         this.showCancelButton = params.showCancelButton ?? this.showCancelButton ?? true;
    32         if (!this.showCancelButton) {
    33             this.cancelButton.style.display = 'none';
    34         }
     24    setConfirmBoxParams(params) {
     25        this.confirmButtonText = params.confirmButtonText ?? this.confirmButtonText ?? wordthree.translations.yes;
     26        this.cancelButtonText  = params.cancelButtonText ?? this.cancelButtonText ?? wordthree.translations.cancel;
     27        this.message           = params.message ?? '';
     28        this.setMessage();
     29        this.confirmButton.textContent = this.confirmButtonText;
     30        this.cancelButton.textContent  = this.cancelButtonText;
     31        this.showCancelButton          = params.showCancelButton ?? this.showCancelButton ?? true;
     32        if (!this.showCancelButton) {
     33            this.cancelButton.style.display = 'none';
     34        }
     35    }
    3536
    36     }
     37    setMessage() {
     38        this.messageField.innerHTML = this.message;
     39    }
    3740
    38     setMessage() {
    39         this.messageField.innerHTML = this.message;
    40     }
     41    open(params = {}, callback) {
     42        this.setConfirmBoxParams(params);
     43        this.callback               = callback;
     44        this.selector.style.display = 'block';
     45        document.body.classList.add('wordthree-confirm-open');
     46    }
    4147
    42     open(params = {}, callback) {
    43         this.setConfirmBoxParams(params);
    44         this.callback = callback;
    45         this.selector.style.display = 'block';
    46         document.body.classList.add('wordthree-confirm-open');
    47     }
     48    close() {
     49        this.selector.style.display = 'none';
     50        document.body.classList.remove('wordthree-confirm-open');
     51        this.callback = null;
     52    }
    4853
    49     close() {
    50         this.selector.style.display = 'none';
    51         document.body.classList.remove('wordthree-confirm-open');
    52         this.callback = null;
    53     }
     54    confirm() {
     55        if (this.callback) {
     56            this.callback(true);
     57        }
     58        this.close();
     59    }
    5460
    55     confirm() {
    56         if (this.callback)
    57             this.callback(true);
    58         this.close();
    59     }
    60 
    61     cancel() {
    62         if (this.callback)
    63             this.callback(false);
    64         this.close();
    65     }
     61    cancel() {
     62        if (this.callback) {
     63            this.callback(false);
     64        }
     65        this.close();
     66    }
    6667}
    67 
    68 /*(function ($, d, w) {
    69     const miniCart = d.querySelector('.mini-cart');
    70     //const confirmBox = d.getElementById('confirm-box');
    71     let totalCartItems = 0;
    72     const countryChangerForm = d.getElementById('country-changer');
    73     const countrySelectors = d.querySelectorAll('.country-select');
    74     const confirmBox = new EachPersonConfirmBox();
    75 
    76     if (countrySelectors) {
    77         countrySelectors.forEach(function (countrySelector) {
    78             countrySelector.addEventListener('click', function (e) {
    79                 e.preventDefault();
    80                 let selectedCountry = this.dataset.selected ?? 'GB';
    81                 if (countryChangerForm) {
    82                     if (miniCart) {
    83                         let miniCartItemsCountContainer = miniCart.querySelector('.mini-cart-items');
    84                         if (miniCartItemsCountContainer) {
    85                             totalCartItems = Number(miniCartItemsCountContainer.textContent);
    86                         }
    87                     }
    88 
    89                     countryChangerForm.querySelector('#country-select-val').value = selectedCountry;
    90                     if (!isNaN(totalCartItems) && totalCartItems > 0) {
    91                         confirmBox.open('Are you sure? <br/>The product you have added to basket can not be delivered to this country. If you continue the product will be removed.',
    92                             function (confirm) {
    93                                 if (confirm) {
    94                                     countryChangerForm.submit();
    95                                 }
    96                             });
    97                         return;
    98                     }
    99 
    100                     countryChangerForm.submit();
    101                 }
    102             });
    103         })
    104     }
    105 })(jQuery, document, window)*/
  • wordthree/trunk/composer.json

    r2793538 r2862545  
    44    "autoload": {
    55        "psr-4": {
    6             "WordThree\\MetamaskAuth\\": "src/"
     6            "WordThree\\Metamask\\": "src/"
    77        }
    88    },
  • wordthree/trunk/readme.txt

    r2793538 r2862545  
    66Requires at least: 5.0
    77Tested up to: 6.0.2
    8 Stable tag: 1.0.0
     8Stable tag: 1.0.1
    99Requires PHP: 7.0
    1010License: GPLv3 or later
     
    4040= 1.0.0 =
    4141* Plugin release
     42
     43= 1.0.1 =
     44* minor changes to workflow of login js and backend authentication workflow
  • wordthree/trunk/src/Activate.php

    r2793538 r2862545  
    22
    33
    4 namespace WordThree\MetamaskAuth;
     4namespace WordThree\Metamask;
    55
     6class Activate {
    67
    7 class Activate
    8 {
     8    public static function activate() {
     9        static::create_tables();
     10    }
    911
    10     public static function create_tables()
    11     {
    12         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    13         $schema = static::getSchema();
    14         dbDelta($schema);
    15         update_option("wordthree_metamask_db_version", "1.0.0");
    16     }
     12    public static function create_tables() {
     13        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
     14        $schema = static::getSchema();
     15        dbDelta($schema);
     16        update_option('wordthree_metamask_db_version', '1.0.0');
     17    }
    1718
    18     public static function getSchema()
    19     {
    20         global $wpdb;
    21         $db_table_name = $wpdb->prefix . 'twothree_metamask_accounts';  // table name
    22         $charset_collate = $wpdb->get_charset_collate();
     19    public static function getSchema() {
     20        global $wpdb;
     21        $charset_collate = $wpdb->get_charset_collate();
    2322
    24         return "CREATE TABLE IF NOT EXISTS $db_table_name (
    25             `id` bigint(20) NOT NULL AUTO_INCREMENT,
    26             `user_id` bigint(20) UNSIGNED NOT NULL,
    27             `nonce` varchar(18) NOT NULL,
    28             `account_address` varchar(155) NOT NULL,
    29             PRIMARY KEY (`id`),
    30             UNIQUE KEY `account_address` (`account_address`)
    31         ) $charset_collate;";
    32     }
     23        return 'CREATE TABLE ' . $wpdb->prefix . 'twothree_metamask_accounts (
     24            id bigint(20) NOT NULL AUTO_INCREMENT,
     25            user_id bigint(20) UNSIGNED NOT NULL,
     26            nonce varchar(18) NOT NULL,
     27            account_address varchar(155) NOT NULL,
     28            UNIQUE KEY account_address (account_address),
     29            PRIMARY KEY  (id)
     30        ) ' . $charset_collate . ';';
     31    }
    3332}
  • wordthree/trunk/src/AdminSettings.php

    r2793538 r2862545  
    22
    33
    4 namespace WordThree\MetamaskAuth;
    5 
    6 
    7 class AdminSettings
    8 {
    9     /**
    10      * @var AdminSettings|null
    11      */
    12     private static $instance = null;
    13     /**
    14      * @var false|mixed|void
    15      */
    16     private $setting_values = [];
    17 
    18     public function __construct()
    19     {
    20         $this->setting_values = get_option('wordthree_option');
    21         add_action('admin_menu', array($this, 'register_admin_menus'));
    22         add_action('admin_init', array($this, 'settings_page_init'));
    23     }
    24 
    25     public static function instance()
    26     {
    27         if (is_null(self::$instance)) {
    28             self::$instance = new self();
    29         }
    30 
    31         return self::$instance;
    32     }
    33 
    34     public function register_admin_menus()
    35     {
    36         add_menu_page(
    37             esc_html__('WordThree Settings', 'wordthree'),
    38             esc_html__('WordThree Settings', 'wordthree'),
    39             'manage_options',
    40             'wordthree-settings',
    41             [$this, 'admin_settings_page'],
    42             'dashicons-admin-generic'
    43         );
    44     }
    45 
    46     public function admin_settings_page()
    47     {
    48         include_once(WORDTHREE_METAMASK_PLUGIN_PATH . '/views/admin-settings.php');
    49     }
    50 
    51     public function settings_page_init()
    52     {
    53         register_setting(
    54             'wordthree_option_group', // option_group
    55             'wordthree_option' // option_name
    56         //    [ $this, 'sanitize'] // sanitize_callback
    57         );
    58 
    59         add_settings_section(
    60             'wordthree_setting_section_general', // id
    61             esc_html__("General Settings", "wordthree"), // title
    62             null,
    63             //    array($this, 'section_info'), // callback
    64             'wordthree-settings' // page
    65         );
    66 
    67         add_settings_field(
    68             'login_redirect', // id
    69             esc_html__('Redirect after login', 'wordthree'), // title
    70             [$this, 'login_redirect_field'], // callback
    71             'wordthree-settings', // page
    72             'wordthree_setting_section_general' // section
    73         );
    74 
    75         add_settings_section(
    76             'wordthree_setting_section_design', // id
    77             esc_html__("Button Design", "wordthree"), // title
    78             null,
    79             //    array($this, 'section_info'), // callback
    80             'wordthree-settings' // page
    81         );
    82 
    83         add_settings_field(
    84             'button_design', // id
    85             esc_html__('Choose Button Design', 'wordthree'), // title
    86             [$this, 'button_design_field'], // callback
    87             'wordthree-settings', // page
    88             'wordthree_setting_section_design' // section
    89         );
    90 
    91         add_settings_field(
    92             'button_color', // id
    93             esc_html__('Choose Button Color', 'wordthree'), // title
    94             [$this, 'button_color_field'], // callback
    95             'wordthree-settings', // page
    96             'wordthree_setting_section_design' // section
    97         );
    98 
    99     }
    100 
    101     public function section_info()
    102     {
    103         $this->setting_values = get_option('wordthree_option');
    104     }
    105 
    106     public function login_redirect_field()
    107     {
    108         printf('<input type="text" name="wordthree_option[login_redirect_url]" id="login_redirect" value="%s">', $this->setting_values['login_redirect_url'] ?? '');
    109     }
    110 
    111     public function button_design_field()
    112     {
    113         printf('<label id="radio-1" class="radio-design" ><input type="radio" name="wordthree_option[button_design]" id="button_design" %s value="large">Large</label><label id="radio-2" class="radio-design"><input type="radio" name="wordthree_option[button_design]" id="button_design" %s value="compact">Compact</label>', ($this->setting_values['button_design'] ?? 'large') == 'large' ? 'checked' : '', ($this->setting_values['button_design'] ?? 'large') == 'compact' ? 'checked' : '');
    114     }
    115 
    116     public function button_color_field()
    117     {
    118         printf('<label id="button-color-1" class="radio-color" ><input type="radio" name="wordthree_option[button_color]" %s value="light">Light</label><label id="button-color-2" class="radio-color"><input type="radio" name="wordthree_option[button_color]" %s value="dark">Dark</label>', ($this->setting_values['button_color'] ?? 'light') == 'light' ? 'checked' : '', ($this->setting_values['button_color'] ?? 'light') == 'dark' ? 'checked' : '');
    119     }
    120 
    121     public static function metaMaskIcon(){
    122         return file_get_contents(WORDTHREE_METAMASK_PLUGIN_PATH . 'assets/icon/metamask-icon.svg');
    123     }
     4namespace WordThree\Metamask;
     5
     6class AdminSettings {
     7    /**
     8     * Instance of this class
     9     *
     10     * @var AdminSettings|null
     11     */
     12    private static $instance = null;
     13    /**
     14     * Setting Values
     15     *
     16     * @var false|mixed|array
     17     */
     18    private $setting_values = [];
     19
     20    public function __construct() {
     21        $this->setting_values = get_option('wordthree_option');
     22        if (!$this->setting_values) {
     23            $this->setting_values = [];
     24        }
     25
     26        /**
     27         * Register Admin menu
     28         */
     29        add_action('admin_menu', array($this, 'register_admin_menus'));
     30
     31        /**
     32         * Register setting sections and fields
     33         */
     34        add_action('admin_init', array($this, 'settings_page_init'));
     35
     36        /**
     37         * Apply default values before saving the options
     38         */
     39        add_filter('pre_update_option_wordthree_option', [$this, 'set_default_values']);
     40    }
     41
     42    /**
     43     * Instance of this class
     44     *
     45     * @return AdminSettings|null
     46     */
     47    public static function instance() {
     48        if (is_null(self::$instance)) {
     49            self::$instance = new self();
     50        }
     51
     52        return self::$instance;
     53    }
     54
     55    /**
     56     * Set default values before saving the option
     57     * Callback function for pre_update_option_{$option} filter hook
     58     *
     59     * @param $value
     60     * @return array|object|string
     61     * @see update_option()
     62     */
     63    public function set_default_values( $value) {
     64        $defaultValues = [
     65            'login_redirect' => '',
     66            'button_design' => 'large',
     67            'button_color' => 'light',
     68            'enable_metamask_login' => 'off',
     69            'enable_metamask_register' => 'off',
     70            'display_on_login_page' => 'off',
     71            'display_on_register_page' => 'off',
     72            'display_on_woocommerce_account_page' => 'off',
     73            'display_on_woocommerce_register_form' => 'off',
     74            'display_on_woocommerce_login_form' => 'off',
     75            'display_on_woocommerce_checkout_form' => 'off',
     76        ];
     77
     78        return wp_parse_args($value, $defaultValues);
     79    }
     80
     81    /**
     82     * Register Admin menu
     83     */
     84    public function register_admin_menus() {
     85        add_menu_page(
     86            esc_html__('WordThree Settings', 'wordthree'),
     87            esc_html__('WordThree Settings', 'wordthree'),
     88            'manage_options',
     89            'wordthree-settings',
     90            [$this, 'admin_settings_page'],
     91            WORDTHREE_METAMASK_PLUGIN_URL . 'assets/icon/wordthree.png'
     92        );
     93    }
     94
     95    /**
     96     * Displays admin setting page
     97     */
     98    public function admin_settings_page() {
     99        include_once WORDTHREE_METAMASK_PLUGIN_PATH . 'views/admin/settings.php';
     100    }
     101
     102    /**
     103     * Registers setting sections and fields
     104     */
     105    public function settings_page_init() {
     106        register_setting(
     107            'wordthree_option_group', // option_group
     108            'wordthree_option' // option_name,
     109        );
     110
     111        add_settings_section(
     112            'wordthree_setting_section_general', // id
     113            esc_html__('General Settings', 'wordthree'), // title
     114            null,
     115            'wordthree-settings' // page
     116        );
     117
     118        add_settings_field(
     119            'login_redirect', // id
     120            esc_html__('Redirect after login', 'wordthree'), // title
     121            [$this, 'login_redirect_field'], // callback
     122            'wordthree-settings', // page
     123            'wordthree_setting_section_general' // section
     124        );
     125
     126        add_settings_field(
     127            'enable_metamask_login', // id
     128            esc_html__('Enable login with metamask?', 'wordthree'), // title
     129            [$this, 'checkbox'], // callback
     130            'wordthree-settings', // page
     131            'wordthree_setting_section_general', // section
     132            [
     133                'name' => 'enable_metamask_login',
     134                'checked' => $this->enableLogin(),
     135            ]
     136        );
     137
     138        add_settings_field(
     139            'enable_metamask_register', // id
     140            esc_html__('Enable register with metamask?', 'wordthree'), // title
     141            [$this, 'checkbox'], // callback
     142            'wordthree-settings', // page
     143            'wordthree_setting_section_general', // section
     144            [
     145                'name' => 'enable_metamask_register',
     146                'checked' => $this->enableRegister(),
     147            ]
     148        );
     149
     150        add_settings_field(
     151            'enable_account_linking', // id
     152            esc_html__('Enable account linking with metamask?', 'wordthree'), // title
     153            [$this, 'checkbox'], // callback
     154            'wordthree-settings', // page
     155            'wordthree_setting_section_general', // section
     156            [
     157                'name' => 'enable_account_linking',
     158                'checked' => $this->enableLinking(),
     159            ]
     160        );
     161
     162        add_settings_field(
     163            'enable_account_unlinking', // id
     164            esc_html__('Enable account linking with metamask?', 'wordthree'), // title
     165            [$this, 'checkbox'], // callback
     166            'wordthree-settings', // page
     167            'wordthree_setting_section_general', // section
     168            [
     169                'name' => 'enable_account_unlinking',
     170                'checked' => $this->enableUnlinking(),
     171            ]
     172        );
     173
     174        add_settings_section(
     175            'wordthree_setting_section_design', // id
     176            esc_html__('Button Design', 'wordthree'), // title
     177            null,
     178            'wordthree-settings' // page
     179        );
     180
     181        add_settings_field(
     182            'button_design', // id
     183            esc_html__('Choose Button Design', 'wordthree'), // title
     184            [$this, 'button_design_field'], // callback
     185            'wordthree-settings', // page
     186            'wordthree_setting_section_design' // section
     187        );
     188
     189        add_settings_field(
     190            'button_color', // id
     191            esc_html__('Choose Button Color', 'wordthree'), // title
     192            [$this, 'button_color_field'], // callback
     193            'wordthree-settings', // page
     194            'wordthree_setting_section_design' // section
     195        );
     196
     197        add_settings_section(
     198            'wordthree_setting_section_wordpress', // id
     199            esc_html__('WordPress', 'wordthree'), // title
     200            null,
     201            'wordthree-settings' // page
     202        );
     203
     204        add_settings_field(
     205            'display_on_login_page', // id
     206            esc_html__('Display on WordPress Login page?', 'wordthree'), // title
     207            [$this, 'checkbox'], // callback
     208            'wordthree-settings', // page
     209            'wordthree_setting_section_wordpress', // section
     210            [
     211                'name' => 'display_on_login_page',
     212                'checked' => $this->displayOnWpLoginPage(),
     213            ]
     214        );
     215
     216        add_settings_field(
     217            'display_on_register_page', // id
     218            esc_html__('Display on WordPress Register page?', 'wordthree'), // title
     219            [$this, 'checkbox'], // callback
     220            'wordthree-settings', // page
     221            'wordthree_setting_section_wordpress', // section
     222            [
     223                'name' => 'display_on_register_page',
     224                'checked' => $this->displayOnWPRegisterPage(),
     225            ]
     226        );
     227
     228        if (class_exists(\WooCommerce::class)) {
     229            add_settings_section(
     230                'wordthree_setting_section_woocommerce', // id
     231                esc_html__('Woocommerce', 'wordthree'), // title
     232                null,
     233                'wordthree-settings' // page
     234            );
     235
     236            add_settings_field(
     237                'display_on_woocommerce_account_page', // id
     238                esc_html__('Display on Woocommerce Account Page?', 'wordthree'), // title
     239                [$this, 'checkbox'], // callback
     240                'wordthree-settings', // page
     241                'wordthree_setting_section_woocommerce', // section
     242                [
     243                    'name' => 'display_on_woocommerce_account_page',
     244                    'checked' => $this->displayOnWoocommerceAccountPage(),
     245                ]
     246            );
     247
     248            add_settings_field(
     249                'display_on_woocommerce_register_form', // id
     250                esc_html__('Display on WooCommerce Register Form?', 'wordthree'), // title
     251                [$this, 'checkbox'], // callback
     252                'wordthree-settings', // page
     253                'wordthree_setting_section_woocommerce', // section
     254                [
     255                    'name' => 'display_on_woocommerce_register_form',
     256                    'checked' => $this->displayOnWoocommerceRegisterForm(),
     257                ]
     258            );
     259
     260            add_settings_field(
     261                'display_on_woocommerce_login_form', // id
     262                esc_html__('Display on WooCommerce Login Form?', 'wordthree'), // title
     263                [$this, 'checkbox'], // callback
     264                'wordthree-settings', // page
     265                'wordthree_setting_section_woocommerce', // section
     266                [
     267                    'name' => 'display_on_woocommerce_login_form',
     268                    'checked' => $this->displayOnWoocommerceLoginForm(),
     269                ]
     270            );
     271
     272            add_settings_field(
     273                'display_on_woocommerce_checkout_form', // id
     274                esc_html__('Display on Checkout Register Form?', 'wordthree'), // title
     275                [$this, 'checkbox'], // callback
     276                'wordthree-settings', // page
     277                'wordthree_setting_section_woocommerce', // section
     278                [
     279                    'name' => 'display_on_woocommerce_checkout_form',
     280                    'checked' => $this->displayOnWoocommerceCheckoutForm(),
     281                ]
     282            );
     283        }
     284
     285    }
     286
     287    /**
     288     * Redirect on login setting field
     289     */
     290    public function login_redirect_field() {
     291        ?>
     292        <input type="text" name="wordthree_option[login_redirect_url]" id="login_redirect"
     293               value="<?php echo esc_url(isset($this->setting_values['login_redirect_url']) ? $this->setting_values['login_redirect_url'] : ''); ?>">
     294        <?php
     295    }
     296
     297    /**
     298     * Button design field
     299     */
     300    public function button_design_field() {
     301        $design = $this->buttonDesign();
     302        ?>
     303        <label id="radio-1" class="radio-design">
     304            <input type="radio" name="wordthree_option[button_design]" id="button_design"
     305                   value="large" <?php checked($design, 'large'); ?>>
     306            <?php esc_html_e('Large', 'wordthree'); ?>
     307        </label>
     308        <label id="radio-2" class="radio-design">
     309            <input type="radio" name="wordthree_option[button_design]" id="button_design"
     310                   value="compact" <?php checked($design, 'compact'); ?>>
     311            <?php esc_html_e('Compact', 'wordthree'); ?>
     312        </label>
     313        <?php
     314    }
     315
     316    /**
     317     * Button color field
     318     */
     319    public function button_color_field() {
     320        $button_color = $this->buttonColor();
     321        ?>
     322        <label id="button-color-1" class="radio-color">
     323            <input type="radio" name="wordthree_option[button_color]"
     324                   value="light" <?php checked($button_color, 'light'); ?>>
     325            <?php esc_html_e('Light', 'wordthree'); ?>
     326        </label>
     327        <label id="button-color-2" class="radio-color">
     328            <input type="radio" name="wordthree_option[button_color]"
     329                   value="dark" <?php checked($button_color, 'dark'); ?>>
     330            <?php esc_html_e('Dark', 'wordthree'); ?>
     331        </label>
     332        <?php
     333    }
     334
     335    /**
     336     * Checkbox field
     337     *
     338     * @param array $args
     339     */
     340    public function checkbox( $args = []) {
     341        $checked = isset($args['checked']) ? esc_attr($args['checked']) : false;
     342        ?>
     343        <input type="checkbox" name="wordthree_option[<?php echo esc_attr($args['name']); ?>]"
     344               value="on" <?php checked($checked); ?>>
     345        <?php
     346    }
     347
     348    /**
     349     * Get Metamask Icon
     350     *
     351     * @return false|string
     352     */
     353    public static function metaMaskIcon() {
     354        return file_get_contents(WORDTHREE_METAMASK_PLUGIN_PATH . 'assets/icon/metamask-icon.svg');
     355    }
     356
     357    /**
     358     * Get Metamask Icon Url
     359     *
     360     * @return string
     361     */
     362    public static function metaMaskIconUrl() {
     363        return WORDTHREE_METAMASK_PLUGIN_URL . 'assets/icon/metamask-icon.svg';
     364    }
     365
     366    public static function metaAttentionIconUrl() {
     367        return WORDTHREE_METAMASK_PLUGIN_URL . 'assets/icon/attention.svg';
     368    }
     369
     370    /**
     371     * Get redirect after login url
     372     *
     373     * @return mixed|string|void
     374     */
     375    public function redirectUrl() {
     376        $redirectUrl = admin_url();
     377        if (isset($this->setting_values['login_redirect_url']) && !empty($this->setting_values['login_redirect_url'])) {
     378            $redirectUrl = $this->setting_values['login_redirect_url'];
     379        }
     380
     381        return esc_url($redirectUrl);
     382    }
     383
     384    /**
     385     * Get button design
     386     *
     387     * @return mixed|string
     388     */
     389    public function buttonDesign() {
     390        $design = 'large';
     391        if (isset($this->setting_values['button_design'])) {
     392            if ($this->setting_values['button_design']) {
     393                $design = $this->setting_values['button_design'];
     394            }
     395        }
     396
     397        return $design;
     398    }
     399
     400    /**
     401     * Get button color
     402     *
     403     * @return mixed|string
     404     */
     405    public function buttonColor() {
     406        $button_color = 'light';
     407        if (isset($this->setting_values['button_color'])) {
     408            if ($this->setting_values['button_color']) {
     409                $button_color = $this->setting_values['button_color'];
     410            }
     411        }
     412
     413        return $button_color;
     414    }
     415
     416    public function enableLogin() {
     417        /**
     418         * Default is true if option is not saved in database yet
     419         */
     420        if (!isset($this->setting_values['enable_metamask_login'])) {
     421            return true;
     422        }
     423
     424        return 'on' == $this->setting_values['enable_metamask_login'];
     425    }
     426
     427    public function enableRegister() {
     428        /**
     429         * Default is true if option is not saved in database yet
     430         */
     431        if (!isset($this->setting_values['enable_metamask_register'])) {
     432            return true;
     433        }
     434
     435        return 'on' == $this->setting_values['enable_metamask_register'];
     436    }
     437
     438    public function enableLinking() {
     439        /**
     440         * Default is true if option is not saved in database yet
     441         */
     442        if (!isset($this->setting_values['enable_account_linking'])) {
     443            return true;
     444        }
     445
     446        return 'on' == $this->setting_values['enable_account_linking'];
     447    }
     448
     449    public function enableUnlinking() {
     450        /**
     451         * Default is true if option is not saved in database yet
     452         */
     453        if (!isset($this->setting_values['enable_account_unlinking'])) {
     454            return true;
     455        }
     456
     457        return 'on' == $this->setting_values['enable_account_unlinking'];
     458    }
     459
     460    public function displayOnWPLoginPage() {
     461        /**
     462         * Default is true if option is not saved in database yet
     463         */
     464        if (!isset($this->setting_values['display_on_login_page'])) {
     465            return true;
     466        }
     467
     468        return 'on' == $this->setting_values['display_on_login_page'];
     469    }
     470
     471    public function displayOnWPRegisterPage() {
     472        /**
     473         * Default is true if option is not saved in database yet
     474         */
     475        if (!isset($this->setting_values['display_on_register_page'])) {
     476            return true;
     477        }
     478
     479        return 'on' == $this->setting_values['display_on_register_page'];
     480    }
     481
     482    public function displayOnWoocommerceAccountPage() {
     483        /**
     484         * Default is true if option is not saved in database yet
     485         */
     486        if (!isset($this->setting_values['display_on_woocommerce_account_page'])) {
     487            return true;
     488        }
     489
     490        return 'on' == $this->setting_values['display_on_woocommerce_account_page'];
     491    }
     492
     493    public function displayOnWoocommerceRegisterForm() {
     494        /**
     495         * Default is true if option is not saved in database yet
     496         */
     497        if (!isset($this->setting_values['display_on_woocommerce_register_form'])) {
     498            return true;
     499        }
     500
     501        return 'on' == $this->setting_values['display_on_woocommerce_register_form'];
     502    }
     503
     504    public function displayOnWoocommerceLoginForm() {
     505        /**
     506         * Default is true if option is not saved in database yet
     507         */
     508        if (!isset($this->setting_values['display_on_woocommerce_login_form'])) {
     509            return true;
     510        }
     511
     512        return 'on' == $this->setting_values['display_on_woocommerce_login_form'];
     513    }
     514
     515    public function displayOnWoocommerceCheckoutForm() {
     516        /**
     517         * Default is true if option is not saved in database yet
     518         */
     519        if (!isset($this->setting_values['display_on_woocommerce_checkout_form'])) {
     520            return true;
     521        }
     522
     523        return 'on' == $this->setting_values['display_on_woocommerce_checkout_form'];
     524    }
    124525}
  • wordthree/trunk/src/AuthManager.php

    r2793538 r2862545  
    11<?php
    22
    3 
    4 namespace WordThree\MetamaskAuth;
    5 
    6 
    7 use Elliptic\Curve\BaseCurve\Point;
    8 use Elliptic\EC;
    9 use kornrunner\Keccak;
    10 
    11 class AuthManager
    12 {
    13     const MESSAGE = 'Sign this message to validate that you are the owner of the account. Nonce string: %s';
    14 
    15     /**
    16      * @var AuthManager|null
    17      */
    18     private static $instance = null;
    19 
    20     /**
    21      * Table name
    22      * @var string $tablename
    23      */
    24     public $tablename;
    25 
    26     /**
    27      * Table name without prefix
    28      * @var string
    29      */
    30     static $tablename_without_prefix = 'twothree_metamask_accounts';
    31 
    32     /**
    33      * @var \wpdb
    34      */
    35     private $wpdb;
    36 
    37     public function __construct()
    38     {
    39         global $wpdb;
    40         $this->wpdb = $wpdb;
    41         $this->tablename = $wpdb->prefix . self::$tablename_without_prefix;
    42     }
    43 
    44     public static function instance()
    45     {
    46         if (is_null(self::$instance)) {
    47             self::$instance = new self();
    48         }
    49 
    50         return self::$instance;
    51     }
    52 
    53     function saveNonce($address, $nonce)
    54     {
    55         $result = $this->wpdb->get_row("SELECT * FROM $this->tablename WHERE account_address='$address'");
    56         if ($result) {
    57             return $this->updateNonce($address, $nonce);
    58         }
    59 
    60         return $this->wpdb->insert($this->tablename, [
    61             'user_id' => -1,
    62             'account_address' => $address,
    63             'nonce' => $nonce,
    64         ]);
    65     }
    66 
    67     function updateNonce($address, $nonce)
    68     {
    69         if ($this->wpdb->update($this->tablename,
    70             [
    71                 'nonce' => $nonce
    72             ],
    73             [
    74                 'account_address' => $address
    75             ])) {
    76             return true;
    77         }
    78 
    79         return false;
    80     }
    81 
    82     /**
    83      * Helper function to check if the request contains required parameters.
    84      * @param $request \WP_REST_Request
    85      * @return bool
    86      * @throws \Exception
    87      */
    88     public function verify_request($request)
    89     {
    90         $address = esc_sql($request->get_param('address'));
    91 
    92         $result = $this->wpdb->get_row("SELECT * FROM  $this->tablename WHERE account_address = '$address'");
    93 
    94         if ($result) {
    95             return $this->verifySignature(sprintf(__(AuthManager::MESSAGE), $result->nonce), $request->get_param('signature'), $request->get_param('address'));
    96         }
    97         return false;
    98     }
    99 
    100     /**
    101      * Verify if the signature retrieved from the user is genuine.
    102      * @param $message string
    103      * @param $signature string
    104      * @param $address string
    105      * @return bool
    106      * @throws \Exception
    107      */
    108     function verifySignature($message, $signature, $address)
    109     {
    110         $msglen = strlen($message);
    111         $hash = Keccak::hash("\x19Ethereum Signed Message:\n{$msglen}{$message}", 256);
    112         $sign = [
    113             "r" => substr($signature, 2, 64),
    114             "s" => substr($signature, 66, 64)
    115         ];
    116         $recid = ord(hex2bin(substr($signature, 130, 2))) - 27;
    117         if ($recid != ($recid & 1))
    118             return false;
    119 
    120         $ec = new EC('secp256k1');
    121 
    122         $pubkey = $ec->recoverPubKey($hash, $sign, $recid);
    123         return $address == $this->pubKeyToAddress($pubkey);
    124     }
    125 
    126     /**
    127      * Transforms the public key to a hexadecimal address.
    128      * @param $pubkey Point
    129      * @return string
    130      */
    131     function pubKeyToAddress($pubkey)
    132     {
    133         return "0x" . substr(Keccak::hash(substr(hex2bin($pubkey->encode("hex")), 1), 256), 24);
    134     }
    135 
    136     function login_user($address)
    137     {
    138         wp_clear_auth_cookie();
    139         $user = $this->get_user_by_address($address);
    140         if ($user) {
    141             $user_id = $user->ID;
    142             wp_set_current_user($user_id, $address);
    143             wp_set_auth_cookie($user_id);
    144             return true;
    145         }
    146 
    147         $createdUserID = $this->create_user($address);
    148         if ($createdUserID) {
    149             wp_set_current_user($createdUserID, $address);
    150             wp_set_auth_cookie($createdUserID);
    151             return true;
    152         }
    153 
    154         return false;
    155     }
    156 
    157     /**
    158      * Create a new WordPress user account and link the address with the user id.
    159      * @param $address string
    160      * @return bool|int
    161      */
    162     function create_user($address)
    163     {
    164         /**
    165          * return user by login if user was already created using the wallet address
    166          */
    167         $check = get_user_by('login', $address);
    168         if ($check) {
    169             $this->wpdb->update($this->tablename,
    170                 array(
    171                     'user_id' => $check->ID,
    172                 ),
    173                 [
    174                     "account_address" => $address,
    175                 ]);
    176             return $check->ID;
    177         }
    178 
    179         $currentUser = wp_create_user($address, wp_generate_password(), null);
    180 
    181         if (!is_wp_error($currentUser)) {
    182             $this->wpdb->update($this->tablename,
    183                 array(
    184                     'user_id' => $currentUser,
    185                 ),
    186                 [
    187                     "account_address" => $address,
    188                 ]);
    189             return $currentUser;
    190         }
    191         return false;
    192     }
    193 
    194     /**
    195      * check if user account already exists
    196      * @param $address
    197      * @return bool
    198      */
    199     function checkAccountExists($address)
    200     {
    201         $userByAddress = $this->get_user_by_address($address);
    202         if ($userByAddress) {
    203             return true;
    204         }
    205 
    206         $check = get_user_by('login', $address);
    207         if ($check) {
    208             return true;
    209         }
    210 
    211         return false;
    212     }
    213 
    214     /**
    215      * Link an existing WordPress user account to metamask
    216      * @param int $userID
    217      * @param string $address
    218      * @return bool
    219      */
    220     public function link_account_to_metamask($userID, $address)
    221     {
    222         $userByAddress = $this->get_user_by_address($address);
    223         if ($userByAddress) {
    224             return true;
    225         }
    226 
    227         return $this->wpdb->update($this->tablename,
    228             array(
    229                 'user_id' => $userID,
    230             ),
    231             [
    232                 "account_address" => $address,
    233             ]);
    234     }
    235 
    236     /**
    237      * Unlink a WordPress user account from metamask login
    238      * @param $address string
    239      * @return bool
    240      */
    241     public function unlink_user($address)
    242     {
    243         $userByAddress = $this->get_user_by_address($address);
    244         if (!$userByAddress) {
    245             return true;
    246         }
    247 
    248         if ($this->wpdb->delete($this->tablename,
    249             array(
    250                 'user_id' => $userByAddress->ID
    251             ))) {
    252             return true;
    253         }
    254         return false;
    255     }
    256 
    257     /**
    258      * gets the WP_User by its wallet address.
    259      * @param $address string
    260      * @return false|\WP_User
    261      */
    262     function get_user_by_address($address)
    263     {
    264         $address = esc_sql($address);
    265         $result = $this->wpdb->get_row("SELECT * FROM  $this->tablename WHERE account_address = '$address'");
    266         if (!$result) {
    267             return false;
    268         }
    269         return get_user_by('id', $result->user_id);
    270     }
    271 
    272     /**
    273      * check if given user id is linked to metamask
    274      * @param int $userID
    275      * @return array|false|object|\stdClass
    276      * returns false if not linked otherwise user metamask info
    277      */
    278     public function checkLinkedWithMetamask($userID)
    279     {
    280         $result = $this->wpdb->get_row("SELECT * FROM  $this->tablename WHERE user_id = $userID");
    281         if (!$result) {
    282             return false;
    283         }
    284 
    285         return $result;
    286     }
    287 
    288 
     3namespace WordThree\Metamask;
     4
     5class AuthManager {
     6
     7    const MESSAGE = 'Sign this message to validate that you are the owner of the account. Nonce string: %s';
     8
     9    /**
     10     * Instance of this class
     11     *
     12     * @var AuthManager|null
     13     */
     14    private static $instance = null;
     15
     16    /**
     17     * AuthManager constructor.
     18     */
     19    public function __construct() {
     20
     21    }
     22
     23    /**
     24     * Instance of the class
     25     *
     26     * @return AuthManager|null
     27     */
     28    public static function instance() {
     29        if (is_null(self::$instance)) {
     30            self::$instance = new self();
     31        }
     32
     33        return self::$instance;
     34    }
     35
     36    /**
     37     * Generate and save nonce
     38     *
     39     * @param string $address
     40     * @return false|string
     41     * @throws \Exception
     42     */
     43    public function generate_nonce( $address) {
     44        $nonce = bin2hex(random_bytes(5));
     45
     46        if ($this->saveNonce($address, $nonce)) {
     47            return $nonce;
     48        }
     49
     50        return false;
     51    }
     52
     53    /**
     54     * Save nonce
     55     *
     56     * @param string $address
     57     * @param string $nonce
     58     * @return bool|int
     59     */
     60    public function saveNonce( $address, $nonce) {
     61        global $wpdb;
     62        $result = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'twothree_metamask_accounts WHERE account_address=%s', $address));
     63        if ($result) {
     64            return $this->updateNonce($address, $nonce);
     65        }
     66
     67        return $wpdb->insert($wpdb->prefix . 'twothree_metamask_accounts', [
     68            'user_id' => -1,
     69            'account_address' => $address,
     70            'nonce' => $nonce,
     71        ]);
     72    }
     73
     74    /**
     75     * Update Nonce
     76     *
     77     * @param string $address
     78     * @param string $nonce
     79     * @return bool
     80     */
     81    public function updateNonce( $address, $nonce) {
     82        global $wpdb;
     83        if ($wpdb->update($wpdb->prefix . 'twothree_metamask_accounts',
     84            [
     85                'nonce' => $nonce
     86            ],
     87            [
     88                'account_address' => $address
     89            ])) {
     90            return true;
     91        }
     92
     93        return false;
     94    }
     95
     96    /**
     97     * Helper function to check if the request contains required parameters.
     98     *
     99     * @param $request \WP_REST_Request
     100     * @return bool
     101     */
     102    public function verify_request( $request) {
     103        global $wpdb;
     104        $address = $request->get_param('address');
     105        $result  = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'twothree_metamask_accounts WHERE account_address = %s', $address));
     106
     107        if ($result) {
     108            return VerifyPersonalSignature::verify(sprintf(__(self::MESSAGE), $result->nonce), $request->get_param('signature'), $request->get_param('address'));
     109        }
     110        return false;
     111    }
     112
     113    /**
     114     * Login User using provided wallet address
     115     *
     116     * @param string $address
     117     * @return bool
     118     */
     119    public function login_user( $address) {
     120        wp_clear_auth_cookie();
     121        $user = $this->get_user_by_address($address);
     122        if ($user) {
     123            $user_id = $user->ID;
     124            wp_set_current_user($user_id, $address);
     125            wp_set_auth_cookie($user_id);
     126            return true;
     127        }
     128
     129        $createdUserID = $this->create_user($address);
     130        if ($createdUserID) {
     131            wp_set_current_user($createdUserID, $address);
     132            wp_set_auth_cookie($createdUserID);
     133            return true;
     134        }
     135
     136        return false;
     137    }
     138
     139    /**
     140     * Create a new WordPress user account and link the address with the user id.
     141     *
     142     * @param $address string
     143     * @return bool|int
     144     */
     145    public function create_user( $address) {
     146        global $wpdb;
     147        /**
     148         * Return user by login if user was already created using the wallet address
     149         */
     150        $check = get_user_by('login', $address);
     151        if ($check) {
     152            $wpdb->update($wpdb->prefix . 'twothree_metamask_accounts',
     153                array(
     154                    'user_id' => $check->ID,
     155                ),
     156                [
     157                    'account_address' => $address,
     158                ]);
     159            return $check->ID;
     160        }
     161
     162        $currentUser = wp_create_user($address, wp_generate_password(), null);
     163
     164        if (!is_wp_error($currentUser)) {
     165            $wpdb->update($wpdb->prefix . 'twothree_metamask_accounts',
     166                array(
     167                    'user_id' => $currentUser,
     168                ),
     169                [
     170                    'account_address' => $address,
     171                ]);
     172            return $currentUser;
     173        }
     174        return false;
     175    }
     176
     177    /**
     178     * Check if user account already exists
     179     *
     180     * @param $address
     181     * @return bool
     182     */
     183    public function checkAccountExists( $address) {
     184        $userByAddress = $this->get_user_by_address($address);
     185        if ($userByAddress) {
     186            return true;
     187        }
     188
     189        $check = get_user_by('login', $address);
     190        if ($check) {
     191            return true;
     192        }
     193
     194        return false;
     195    }
     196
     197    /**
     198     * Link an existing WordPress user account to metamask
     199     *
     200     * @param int $userID
     201     * @param string $address
     202     * @return bool
     203     */
     204    public function link_account_to_metamask( $userID, $address) {
     205        global $wpdb;
     206
     207        return $wpdb->update($wpdb->prefix . 'twothree_metamask_accounts',
     208            array(
     209                'user_id' => $userID,
     210            ),
     211            [
     212                'account_address' => $address,
     213            ]);
     214    }
     215
     216    /**
     217     * Unlink a WordPress user account from metamask login
     218     *
     219     * @param string $address
     220     * @return bool
     221     */
     222    public function unlink_user( $address) {
     223        global $wpdb;
     224        $userByAddress = $this->get_user_by_address($address);
     225        if (!$userByAddress) {
     226            return true;
     227        }
     228
     229        if ($wpdb->delete($wpdb->prefix . 'twothree_metamask_accounts',
     230            array(
     231                'user_id' => $userByAddress->ID
     232            ))) {
     233            return true;
     234        }
     235        return false;
     236    }
     237
     238    /**
     239     * Get the WP_User by its wallet address.
     240     *
     241     * @param string $address
     242     * @return false|\WP_User
     243     */
     244    public function get_user_by_address( $address) {
     245        global $wpdb;
     246        $result = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'twothree_metamask_accounts WHERE account_address = %s', $address));
     247        if (!$result) {
     248            return false;
     249        }
     250        return get_user_by('id', $result->user_id);
     251    }
     252
     253    /**
     254     * Check if given user id is linked to metamask
     255     * Returns false if not linked otherwise user metamask info
     256     *
     257     * @param int $userID
     258     * @return array|false|object|\stdClass
     259     *
     260     */
     261    public function checkLinkedWithMetamask( $userID) {
     262        global $wpdb;
     263        $result = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'twothree_metamask_accounts WHERE user_id = %d', $userID));
     264        if (!$result) {
     265            return false;
     266        }
     267
     268        return $result;
     269    }
    289270}
  • wordthree/trunk/src/Metamask.php

    r2793538 r2862545  
    11<?php
    22
     3namespace WordThree\Metamask;
    34
    4 namespace WordThree\MetamaskAuth;
     5use WordThree\Metamask\Pro\MetamaskPro;
    56
     7class Metamask {
     8    /**
     9     * Instance of this class
     10     *
     11     * @var Metamask|null
     12     */
     13    private static $instance = null;
    614
    7 class Metamask
    8 {
    9     /**
    10      * @var Metamask|null
    11      */
    12     private static $instance = null;
     15    /**
     16     * Metamask constructor.
     17     */
     18    private function __construct() {
     19        /**
     20         * Enqueue scripts
     21         */
     22        add_action('login_enqueue_scripts', [$this, 'enqueue_scripts']);
     23        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
     24        add_action('admin_enqueue_scripts', [$this, 'admin_enqueue_scripts']);
    1325
    14     private function __construct()
    15     {
    16         register_activation_hook(WORDTHREE_METAMASK_PLUGIN_FILE, [Activate::class, 'create_tables']);
     26        /**
     27         * Popup modal in footer
     28         */
     29        add_action('login_footer', [$this, 'popup_modal']);
     30        add_action('wp_footer', [$this, 'popup_modal']);
    1731
     32        /**
     33         * Add rest api routes
     34         */
     35        RestRoutes::instance();
    1836
    19         add_action('login_enqueue_scripts', [$this, 'enqueue_scripts']);
    20         add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
    21         add_action('admin_enqueue_scripts', [$this, 'admin_enqueue_scripts']);
    22         add_action('login_footer', [$this, 'popup_modal']);
    23         add_action('wp_footer', [$this, 'popup_modal']);
    24         /**
    25          * add rest api routes
    26          */
    27         RestRoutes::instance();
    28         /**
    29          * add shortcodes
    30          */
    31         Shortcodes::instance();
     37        /**
     38         * Add shortcodes
     39         */
     40        Shortcodes::instance();
    3241
    33         AdminSettings::instance();
    34     }
     42        /**
     43         * Admin settings
     44         */
     45        AdminSettings::instance();
    3546
    36     public static function instance()
    37     {
    38         if (is_null(self::$instance)) {
    39             self::$instance = new self();
    40         }
     47        /**
     48         * Menu customizer
     49         * Adds login via metamask button in menu
     50         */
     51        MenuCustomizer::instance();
    4152
    42         return self::$instance;
    43     }
     53        if (class_exists(MetamaskPro::class)) {
     54            MetamaskPro::instance();
     55        }
     56    }
    4457
    45     function enqueue_scripts()
    46     {
    47         wp_enqueue_style('wordthree-metamask-login-style', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/css/main.css', [], WORDTHREE_METAMASK_PLUGIN_VERSION);
    48         wp_enqueue_script('wordthree-metamask-popup', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/js/popup-modal.js', [], WORDTHREE_METAMASK_PLUGIN_VERSION, true);
    49         wp_enqueue_script('wordthree-metamask-login', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/js/metamask-login.js', [], WORDTHREE_METAMASK_PLUGIN_VERSION, true);
    50         wp_localize_script('wordthree-metamask-login', 'wordthree', [
    51             'nonce' => wp_create_nonce('wp_rest'),
    52             'apiUrl' => get_rest_url(),
    53             'tokenUrl' => RestRoutes::NAMESPACE . '/generate-nonce',
    54             'loginUrl' => RestRoutes::NAMESPACE . '/login',
    55             'registerUrl' => RestRoutes::NAMESPACE . '/register',
    56             'unlinkUrl' => RestRoutes::NAMESPACE . '/unlink',
    57             'linkUrl' => RestRoutes::NAMESPACE . '/link',
    58         ]);
    59     }
     58    /**
     59     * Instance of the class
     60     *
     61     * @return Metamask|null
     62     */
     63    public static function instance() {
     64        if (is_null(self::$instance)) {
     65            self::$instance = new self();
     66        }
    6067
    61     function admin_enqueue_scripts()
    62     {
    63         wp_enqueue_style('wordthree-metamask-style', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/css/admin.css', [], WORDTHREE_METAMASK_PLUGIN_VERSION);
    64     }
     68        return self::$instance;
     69    }
    6570
    66     function popup_modal(){
    67         include_once(WORDTHREE_METAMASK_PLUGIN_PATH . '/views/popup.php');
    68     }
     71    /**
     72     * Enqueue scripts and styles
     73     * And js localized values, text translation for js
     74     */
     75    public function enqueue_scripts() {
     76        wp_enqueue_style('wordthree-metamask-login-style', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/css/main.css', [], WORDTHREE_METAMASK_PLUGIN_VERSION);
     77        wp_enqueue_script('wordthree-web3', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/js/web3.min.js', [], WORDTHREE_METAMASK_PLUGIN_VERSION, true);
     78        wp_enqueue_script('wordthree-metamask-popup', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/js/popup-modal.js', [], WORDTHREE_METAMASK_PLUGIN_VERSION, true);
     79        wp_enqueue_script('wordthree-metamask', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/js/metamask.js', ['wordthree-web3'], WORDTHREE_METAMASK_PLUGIN_VERSION, true);
     80        wp_enqueue_script('wordthree-metamask-login', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/js/metamask-login.js', ['wordthree-metamask-popup'], WORDTHREE_METAMASK_PLUGIN_VERSION, true);
     81        $localizedValues = static::localizedValues();
     82        if (class_exists(MetamaskPro::class)) {
     83            $localizedValues = array_merge($localizedValues, MetamaskPro::localizedValues());
     84        }
     85        wp_localize_script('wordthree-web3', 'wordthree', $localizedValues);
     86    }
     87
     88    public static function localizedValues() {
     89        return [
     90            'translations' => [
     91                'yes' => __('Yes', 'wordthree'),
     92                'cancel' => __('Cancel', 'wordthree'),
     93                'ok' => __('Ok', 'wordthree'),
     94                'metamask_required_login' => __('MetaMask browser extension should be installed in order to use the login.', 'wordthree'),
     95                'install_now' => __('Install Now', 'wordthree'),
     96            ],
     97            'nonce' => wp_create_nonce('wp_rest'),
     98            'apiUrl' => get_rest_url(),
     99            'restRoutes' => [
     100                'tokenUrl' => RestRoutes::REST_ROUTE_NAMESPACE . '/generate-nonce',
     101                'loginUrl' => RestRoutes::REST_ROUTE_NAMESPACE . '/login',
     102                'registerUrl' => RestRoutes::REST_ROUTE_NAMESPACE . '/register',
     103                'unlinkUrl' => RestRoutes::REST_ROUTE_NAMESPACE . '/unlink',
     104                'linkUrl' => RestRoutes::REST_ROUTE_NAMESPACE . '/link',
     105            ]
     106        ];
     107    }
     108
     109    /**
     110     * Enqueue admin scripts and styles
     111     */
     112    public function admin_enqueue_scripts() {
     113        wp_enqueue_style('wordthree-metamask-style', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/css/admin.css', [], WORDTHREE_METAMASK_PLUGIN_VERSION);
     114        wp_enqueue_script('wordthree-admin', WORDTHREE_METAMASK_PLUGIN_URL . 'assets/js/admin.js', ['jquery'], WORDTHREE_METAMASK_PLUGIN_VERSION, true);
     115    }
     116
     117    /**
     118     * Popup modal view
     119     * Loaded in footer
     120     */
     121    public function popup_modal() {
     122        include_once WORDTHREE_METAMASK_PLUGIN_PATH . 'views/popup.php';
     123    }
    69124}
  • wordthree/trunk/src/RestRoutes.php

    r2793538 r2862545  
    22
    33
    4 namespace WordThree\MetamaskAuth;
    5 
    6 
    7 class RestRoutes
    8 {
    9     /**
    10      * Namespace where the API endpoints reside
    11      * @var string
    12      */
    13     const NAMESPACE = "wordthree-auth";
    14 
    15     /**
    16      * @var RestRoutes|null
    17      */
    18     private static $instance = null;
    19 
    20     /**
    21      * @var AuthManager
    22      */
    23     private $authManager;
    24 
    25     private function __construct()
    26     {
    27         add_action('rest_api_init', [$this, 'registerRoutes']);
    28         $this->authManager = AuthManager::instance();
    29     }
    30 
    31     public static function instance()
    32     {
    33         if (is_null(self::$instance)) {
    34             self::$instance = new self();
    35         }
    36 
    37         return self::$instance;
    38     }
    39 
    40 
    41     public function registerRoutes()
    42     {
    43         register_rest_route(static::NAMESPACE, '/generate-nonce', array(
    44             'methods' => \WP_REST_Server::CREATABLE,
    45             'callback' => [$this, 'generate_nonce'],
    46             'permission_callback' => function ($request) {
    47                 return true;
    48             },
    49         ));
    50 
    51         register_rest_route(static::NAMESPACE, '/login', array(
    52             'methods' => \WP_REST_Server::CREATABLE,
    53             'callback' => [$this, 'login_metamask'],
    54             'permission_callback' => function ($request) {
    55                 return !is_user_logged_in();
    56             },
    57         ));
    58 
    59         register_rest_route(static::NAMESPACE, '/register', array(
    60             'methods' => \WP_REST_Server::CREATABLE,
    61             'callback' => [$this, 'register_metamask'],
    62             'permission_callback' => function ($request) {
    63                 return !is_user_logged_in();
    64             },
    65         ));
    66 
    67         register_rest_route(static::NAMESPACE, '/link', array(
    68             'methods' => \WP_REST_Server::CREATABLE,
    69             'callback' => [$this, 'link_account_with_metamask'],
    70             'permission_callback' => function ($request) {
    71                 return is_user_logged_in();
    72             },
    73         ));
    74 
    75         register_rest_route(static::NAMESPACE, '/unlink', array(
    76             'methods' => \WP_REST_Server::CREATABLE,
    77             'callback' => [$this, 'unlink_metamask'],
    78             'permission_callback' => function ($request) {
    79                 return is_user_logged_in();
    80             },
    81         ));
    82     }
    83 
    84     /**
    85      * Endpoint that generates the message for the user to sign inside their wallet.
    86      * @param $request \WP_REST_Request
    87      * @return \WP_REST_Response
    88      * @throws \Exception
    89      */
    90     function generate_nonce($request)
    91     {
    92         $address = $request->get_param('address');
    93         if (!$address) {
    94             return $this->create_response(false, esc_html__("Address is empty.", "wordthree"));
    95         }
    96 
    97         $nonce = bin2hex(random_bytes(5));
    98         if ($this->authManager->saveNonce($address, $nonce)) {
    99             return $this->create_response(true, sprintf(__(AuthManager::MESSAGE, 'wordthree'), $nonce), 200, ["nonce" => $nonce]);
    100         }
    101 
    102         return $this->create_response(true, sprintf(__(AuthManager::MESSAGE, 'wordthree'), $nonce), 200, ["nonce" => $nonce]);
    103     }
    104 
    105     /**
    106      * Endpoint for logging in a Wallet to an already existing WordPress account
    107      * or create new account if account does not exist
    108      * @param $request \WP_REST_Request
    109      * @return \WP_REST_Response
    110      */
    111     function login_metamask($request)
    112     {
    113         try {
    114             $validSignatureVerification = $this->authManager->verify_request($request);
    115             if ($validSignatureVerification) {
    116                 if ($this->authManager->login_user($request->get_param('address'))) {
    117                     return $this->create_response(true, __('Login Successful', 'wordthree'));
    118                 }
    119                 return $this->create_response(false, __('Login failed', 'wordthree'));
    120             }
    121 
    122             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    123         } catch (\Exception $e) {
    124             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    125         }
    126     }
    127 
    128     /**
    129      * Endpoint for registering user using Wallet.
    130      * @param $request \WP_REST_Request
    131      * @return \WP_REST_Response
    132      */
    133     function register_metamask($request)
    134     {
    135         try {
    136             $validSignatureVerification = $this->authManager->verify_request($request);
    137             if ($validSignatureVerification) {
    138 
    139                 if ($this->authManager->checkAccountExists($request->get_param('address'))) {
    140                     return $this->create_response(false, __('Account already Exists', 'wordthree'));
    141                 }
    142 
    143                 if ($this->authManager->login_user($request->get_param('address'))) {
    144                     return $this->create_response(true, __('Registration Successful', 'wordthree'));
    145                 }
    146 
    147                 return $this->create_response(false, __('Registration failed', 'wordthree'));
    148             }
    149             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    150         } catch (\Exception $e) {
    151             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    152         }
    153     }
    154 
    155     /**
    156      * Endpoint for linking existing wp account with metamask.
    157      * @param $request \WP_REST_Request
    158      * @return \WP_REST_Response
    159      */
    160     function link_account_with_metamask($request)
    161     {
    162         try {
    163             $validSignatureVerification = $this->authManager->verify_request($request);
    164             if ($validSignatureVerification) {
    165                 if ($this->authManager->link_account_to_metamask(get_current_user_id(), $request->get_param('address'))) {
    166                     return $this->create_response(true, __('Account Link successful', 'wordthree'));
    167                 }
    168 
    169                 return $this->create_response(false, __('Account Link failed', 'wordthree'));
    170             }
    171 
    172             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    173         } catch (\Exception $e) {
    174             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    175         }
    176     }
    177 
    178     /**
    179      * Endpoint for unlinking an account from metamask.
    180      * @param $request \WP_REST_Request
    181      * @return \WP_REST_Response
    182      */
    183     function unlink_metamask($request)
    184     {
    185         try {
    186             $validSignatureVerification = $this->authManager->verify_request($request);
    187             if ($validSignatureVerification) {
    188                 if ($this->authManager->unlink_user($request->get_param('address'))) {
    189                     return $this->create_response(true, __('Unlink Successful', 'wordthree'));
    190                 }
    191 
    192                 return $this->create_response(false, __('Error Unlinking Account', 'wordthree'));
    193             }
    194 
    195             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    196         } catch (\Exception $e) {
    197             return $this->create_response(false, __('Signature Verification Failed', 'wordthree'));
    198         }
    199     }
    200 
    201     /**
    202      * create a response to send
    203      * @param boolean $success true or false
    204      * @param string $message message to send
    205      * @param int $status status code of the response
    206      * @param array $data array of extra parameters to send with response
    207      * @return \WP_REST_Response
    208      */
    209     function create_response($success, $message, $status = 200, $data = [])
    210     {
    211         return new \WP_REST_Response(
    212             array_merge([
    213                 "success" => $success,
    214                 "message" => $message,
    215             ], $data), $status);
    216     }
     4namespace WordThree\Metamask;
     5
     6class RestRoutes {
     7    /**
     8     * Namespace where the API endpoints reside
     9     *
     10     * @var string
     11     */
     12    const REST_ROUTE_NAMESPACE = 'wordthree';
     13
     14    /**
     15     * Instance of this class
     16     *
     17     * @var RestRoutes|null
     18     */
     19    private static $instance = null;
     20
     21    /**
     22     * RestRoutes constructor.
     23     */
     24    private function __construct() {
     25        /**
     26         * Initialize rest routes
     27         */
     28        add_action('rest_api_init', [$this, 'registerRoutes']);
     29    }
     30
     31    /**
     32     * Instance of this class
     33     *
     34     * @return RestRoutes|null
     35     */
     36    public static function instance() {
     37        if (is_null(self::$instance)) {
     38            self::$instance = new self();
     39        }
     40
     41        return self::$instance;
     42    }
     43
     44    /**
     45     * Register rest routes
     46     */
     47    public function registerRoutes() {
     48        /**
     49         * Generate nonce rest route
     50         */
     51        register_rest_route(static::REST_ROUTE_NAMESPACE, '/generate-nonce', array(
     52            'methods' => \WP_REST_Server::CREATABLE,
     53            'callback' => [$this, 'generate_nonce'],
     54            'permission_callback' => function ( $request) {
     55                return true;
     56            },
     57        ));
     58
     59        /**
     60         * Login route
     61         */
     62        register_rest_route(static::REST_ROUTE_NAMESPACE, '/login', array(
     63            'methods' => \WP_REST_Server::CREATABLE,
     64            'callback' => [$this, 'login_metamask'],
     65            'permission_callback' => function ( $request) {
     66                return !is_user_logged_in();
     67            },
     68        ));
     69
     70        /**
     71         * Register route
     72         */
     73        register_rest_route(static::REST_ROUTE_NAMESPACE, '/register', array(
     74            'methods' => \WP_REST_Server::CREATABLE,
     75            'callback' => [$this, 'register_metamask'],
     76            'permission_callback' => function ( $request) {
     77                return !is_user_logged_in();
     78            },
     79        ));
     80
     81        /**
     82         * Link account to metamask route
     83         */
     84        register_rest_route(static::REST_ROUTE_NAMESPACE, '/link', array(
     85            'methods' => \WP_REST_Server::CREATABLE,
     86            'callback' => [$this, 'link_account_with_metamask'],
     87            'permission_callback' => function ( $request) {
     88                return is_user_logged_in();
     89            },
     90        ));
     91
     92        /**
     93         * Unlink account from metamask route
     94         */
     95        register_rest_route(static::REST_ROUTE_NAMESPACE, '/unlink', array(
     96            'methods' => \WP_REST_Server::CREATABLE,
     97            'callback' => [$this, 'unlink_metamask'],
     98            'permission_callback' => function ( $request) {
     99                return is_user_logged_in();
     100            },
     101        ));
     102    }
     103
     104    /**
     105     * Endpoint that generates the message for the user to sign inside their wallet.
     106     *
     107     * @param $request \WP_REST_Request
     108     * @return \WP_REST_Response
     109     * @throws \Exception
     110     */
     111    public function generate_nonce( $request) {
     112        $address = $request->get_param('address');
     113        if (!$address) {
     114            return $this->create_response(__('Address is empty.', 'wordthree'), false);
     115        }
     116
     117        $nonce = AuthManager::instance()->generate_nonce($address);
     118        if ($nonce) {
     119            return $this->create_response(sprintf(__(AuthManager::MESSAGE, 'wordthree'), $nonce), true, ['nonce' => $nonce]);
     120        }
     121
     122        return $this->create_response(__('Failed Creating Nonce.'), false);
     123    }
     124
     125    /**
     126     * Endpoint for logging in a Wallet to an already existing WordPress account
     127     * or create new account if account does not exist
     128     *
     129     * @param $request \WP_REST_Request
     130     * @return \WP_REST_Response
     131     */
     132    public function login_metamask( $request) {
     133        if (!AdminSettings::instance()->enableLogin()) {
     134            return static::create_response(__('Login via metamask is disabled', 'wordthree'), false, [], '403');
     135        }
     136
     137        $authManager                = AuthManager::instance();
     138        $validSignatureVerification = $authManager->verify_request($request);
     139        if (!$validSignatureVerification) {
     140            return static::create_response(__('Signature Verification Failed', 'wordthree'), false);
     141        }
     142
     143        if ($authManager->login_user($request->get_param('address'))) {
     144            return static::create_response(__('Login Successful', 'wordthree'), true);
     145        }
     146        return static::create_response(__('Login failed', 'wordthree'), false);
     147    }
     148
     149    /**
     150     * Endpoint for registering user using Wallet.
     151     *
     152     * @param $request \WP_REST_Request
     153     * @return \WP_REST_Response
     154     */
     155    public function register_metamask( $request) {
     156        if (!AdminSettings::instance()->enableRegister()) {
     157            return static::create_response(__('Register via metamask is disabled', 'wordthree'), false, [], '403');
     158        }
     159
     160        $authManager                = AuthManager::instance();
     161        $validSignatureVerification = $authManager->verify_request($request);
     162        if (!$validSignatureVerification) {
     163            return static::create_response(__('Signature Verification Failed', 'wordthree'), false);
     164        }
     165
     166        if ($authManager->checkAccountExists($request->get_param('address'))) {
     167            return static::create_response(__('Account already Exists', 'wordthree'), false);
     168        }
     169
     170        if ($authManager->login_user($request->get_param('address'))) {
     171            return static::create_response(__('Registration Successful', 'wordthree'), true);
     172        }
     173
     174        return static::create_response(__('Registration failed', 'wordthree'), false);
     175    }
     176
     177    /**
     178     * Endpoint for linking existing wp account with metamask.
     179     *
     180     * @param $request \WP_REST_Request
     181     * @return \WP_REST_Response
     182     */
     183    public function link_account_with_metamask( $request) {
     184        if (!AdminSettings::instance()->enableLinking()) {
     185            return static::create_response(__('Link account to metamask is disabled', 'wordthree'), false, [], '403');
     186        }
     187
     188        $authManager                = AuthManager::instance();
     189        $validSignatureVerification = $authManager->verify_request($request);
     190        if (!$validSignatureVerification) {
     191            return static::create_response(__('Signature Verification Failed', 'wordthree'), false);
     192        }
     193
     194        $checkLinked = $authManager->checkLinkedWithMetamask(get_current_user_id());
     195        if ($checkLinked) {
     196            return static::create_response(__('Account is already linked.', 'wordthree'), false);
     197        }
     198        /**
     199         * Check if provided address is already used by another account
     200         */
     201        $userByAddress = $authManager->get_user_by_address($request->get_param('address'));
     202        if ($userByAddress && get_current_user_id() !== $userByAddress->ID) {
     203            return static::create_response(__('This wallet address is already linked with another account.', 'wordthree'), false);
     204        }
     205
     206        if ($authManager->link_account_to_metamask(get_current_user_id(), $request->get_param('address'))) {
     207            return static::create_response(__('Account Link successful', 'wordthree'), true);
     208        }
     209
     210        return static::create_response(__('Account Link failed', 'wordthree'), false);
     211    }
     212
     213    /**
     214     * Endpoint for unlinking an account from metamask.
     215     *
     216     * @param $request \WP_REST_Request
     217     * @return \WP_REST_Response
     218     */
     219    public function unlink_metamask( $request) {
     220        if (!AdminSettings::instance()->enableUnlinking()) {
     221            return static::create_response(__('Unlink account with metamask is disabled', 'wordthree'), false, [], '403');
     222        }
     223
     224        $authManager                = AuthManager::instance();
     225        $validSignatureVerification = $authManager->verify_request($request);
     226        if (!$validSignatureVerification) {
     227            return static::create_response(__('Signature Verification Failed', 'wordthree'), false);
     228        }
     229
     230        if ($authManager->unlink_user($request->get_param('address'))) {
     231            return static::create_response(__('Unlink Successful', 'wordthree'), true);
     232        }
     233
     234        return static::create_response(__('Error Unlinking Account', 'wordthree'), false);
     235    }
     236
     237    /**
     238     * Create a response to send
     239     *
     240     * @param boolean $success true or false
     241     * @param string $message message to send
     242     * @param int $status status code of the response
     243     * @param array $data array of extra parameters to send with response
     244     * @return \WP_REST_Response
     245     */
     246    public static function create_response( $message, $success = true, $data = [], $status = 200) {
     247        return new \WP_REST_Response(
     248            array_merge([
     249                'success' => $success,
     250                'message' => $message,
     251            ], $data), $status);
     252    }
    217253}
  • wordthree/trunk/src/Shortcodes.php

    r2793538 r2862545  
    22
    33
    4 namespace WordThree\MetamaskAuth;
     4namespace WordThree\Metamask;
    55
     6use WordThree\Metamask\Shortcodes\Link;
     7use WordThree\Metamask\Shortcodes\Login;
     8use WordThree\Metamask\Shortcodes\Register;
    69
    7 use WordThree\MetamaskAuth\Shortcodes\Link;
    8 use WordThree\MetamaskAuth\Shortcodes\Login;
    9 use WordThree\MetamaskAuth\Shortcodes\Register;
     10class Shortcodes {
    1011
    11 class Shortcodes
    12 {
    13     /**
    14     * @var Shortcodes|null
    15     */
    16     private static $instance = null;
     12    /**
     13     * Instance of this class
     14     *
     15    * @var Shortcodes|null
     16    */
     17    private static $instance = null;
    1718
    18     private function __construct()
    19     {
    20         /**
    21          * initialize shortcodes
    22          */
    23         Login::instance();
    24         Link::instance();
    25         Register::instance();
    26     }
     19    /**
     20     * Shortcodes constructor.
     21     */
     22    private function __construct() {
     23        /**
     24         * Initialize shortcodes
     25         */
    2726
    28     public static function instance()
    29     {
    30         if (is_null(self::$instance)) {
    31             self::$instance = new self();
    32         }
     27        /**
     28         * Login shortcode
     29         */
     30        Login::instance();
    3331
    34         return self::$instance;
    35     }
     32        /**
     33         * Link Account shortcode
     34         */
     35        Link::instance();
     36
     37        /**
     38         * Register Shortcode
     39         */
     40        Register::instance();
     41    }
     42
     43    /**
     44     * Instance of the class
     45     *
     46     * @return Shortcodes|null
     47     */
     48    public static function instance() {
     49        if (is_null(self::$instance)) {
     50            self::$instance = new self();
     51        }
     52
     53        return self::$instance;
     54    }
    3655}
  • wordthree/trunk/src/Shortcodes/Link.php

    r2793538 r2862545  
    22
    33
    4 namespace WordThree\MetamaskAuth\Shortcodes;
     4namespace WordThree\Metamask\Shortcodes;
    55
     6use WordThree\Metamask\AdminSettings;
     7use WordThree\Metamask\AuthManager;
    68
    7 use WordThree\MetamaskAuth\AdminSettings;
    8 use WordThree\MetamaskAuth\AuthManager;
     9class Link {
     10    /**
     11     * Shortcode tag
     12     *
     13     * @var string
     14     */
     15    const SHORTCODE_TAG = 'wordthree_metamask_link';
    916
    10 class Link
    11 {
    12     const SHORTCODE_TAG = 'wordthree_metamask_link';
     17    /**
     18     * Instance of the class or null
     19     *
     20     * @var Link|null
     21     */
     22    private static $instance = null;
    1323
    14     /**
    15      * @var Link|null
    16      */
    17     private static $instance = null;
     24    /**
     25     * Link constructor.
     26     */
     27    private function __construct() {
     28        add_shortcode(static::SHORTCODE_TAG, [$this, 'render']);
     29        /**
     30         * If display on woocommerce myaccount page
     31         */
     32        if (AdminSettings::instance()->displayOnWoocommerceAccountPage()) {
     33            add_action('woocommerce_after_edit_account_form', function () {
     34                echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
     35            });
    1836
    19     private function __construct()
    20     {
    21         add_shortcode(static::SHORTCODE_TAG, [$this, 'render']);
     37            add_action('woocommerce_after_my_account', function () {
     38                echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
     39            });
     40        }
     41    }
    2242
    23         add_action("woocommerce_after_edit_account_form", function () {
    24             echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
    25         });
     43    /**
     44     * Instance of the class
     45     *
     46     * @return Link|null
     47     */
     48    public static function instance() {
     49        if (is_null(self::$instance)) {
     50            self::$instance = new self();
     51        }
    2652
    27         add_action("woocommerce_after_my_account", function () {
    28             echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
    29         });
    30     }
     53        return self::$instance;
     54    }
    3155
    32     public static function instance()
    33     {
    34         if (is_null(self::$instance)) {
    35             self::$instance = new self();
    36         }
     56    /**
     57     * Render shortcode
     58     *
     59     * @return string
     60     */
     61    public function render() {
     62        /**
     63         * Not necessary to link or unlink logged out user
     64         */
     65        if (!is_user_logged_in()) {
     66            return '';
     67        }
    3768
    38         return self::$instance;
    39     }
     69        $linked       = AuthManager::instance()->checkLinkedWithMetamask(get_current_user_id());
     70        $design       = AdminSettings::instance()->buttonDesign();
     71        $design_wrap  = ( 'compact' == $design ) ? $design . '-wrap' : 'large-wrap';
     72        $button_color = AdminSettings::instance()->buttonColor();
    4073
    41     public function render()
    42     {
    43         /**
    44          * not necessary to link or unlink logged out user
    45          */
    46         if (!is_user_logged_in()) {
    47             return '';
    48         }
     74        $design_icon = '<span class="icon-metamask ' . $design . '">' . AdminSettings::metaMaskIcon() . '</span>';
     75        if (!$linked) {
     76            /**
     77             * Link Account is disabled
     78             */
     79            if (!AdminSettings::instance()->enableLinking()) {
     80                return '';
     81            }
     82            return '<div class="wt-metamask-btn wt-metamask-link ' . $design_wrap . '"><button type="button" class="wordthree-metamask-btn wordthree-metamask-link ' . $button_color . '">' . $design_icon . esc_html__('Link Account To Metamask', 'wordthree') . '</button></div>';
     83        }
    4984
    50         $setting_values = get_option('wordthree_option');
    51         $linked = AuthManager::instance()->checkLinkedWithMetamask(get_current_user_id());
    52         $design = $setting_values['button_design'] ?? $setting_values['button_design'] ?: 'large';
    53         $design_wrap = ($design == 'compact') ? $design . '-wrap' : 'large-wrap';
    54         $button_color = $setting_values['button_color'] ?? $setting_values['button_color'] ?: 'light';
    55         $design_icon = '<span class="icon-metamask ' . $design . '">' . AdminSettings::metaMaskIcon() . '</span>';
    56         if (!$linked) {
    57             return '<div class="wt-metamask-btn wt-metamask-link ' . $design_wrap . '"><button type="button" class="wordthree-metamask-btn wordthree-metamask-link ' . $button_color . '">' . $design_icon . esc_html__('Link Account To Metamask', 'wordthree') . '</button></div>';
    58         }
    59 
    60         return '<div class="wt-metamask-btn wt-metamask-unlink ' . $design_wrap . '"><button type="button" class="wordthree-metamask-btn wordthree-metamask-unlink ' . $button_color . '">' . $design_icon . esc_html__('Unlink Account With Metamask', 'wordthree') . '</button></div>';
    61     }
     85        /**
     86         * Unlinking is disabled
     87         */
     88        if (!AdminSettings::instance()->enableUnlinking()) {
     89            return '';
     90        }
     91        return '<div class="wt-metamask-btn wt-metamask-unlink ' . $design_wrap . '"><button type="button" class="wordthree-metamask-btn wordthree-metamask-unlink ' . $button_color . '">' . $design_icon . esc_html__('Unlink Account With Metamask', 'wordthree') . '</button></div>';
     92    }
    6293}
  • wordthree/trunk/src/Shortcodes/Login.php

    r2793538 r2862545  
    22
    33
    4 namespace WordThree\MetamaskAuth\Shortcodes;
     4namespace WordThree\Metamask\Shortcodes;
    55
     6use WordThree\Metamask\AdminSettings;
    67
    7 use WordThree\MetamaskAuth\AdminSettings;
     8class Login {
     9    /**
     10     * Shortcode tag
     11     *
     12     * @var string
     13     */
     14    const SHORTCODE_TAG = 'wordthree_metamask_login';
    815
    9 class Login
    10 {
    11     const SHORTCODE_TAG = 'wordthree_metamask_login';
    12     /**
    13      * @var Login|null
    14      */
    15     private static $instance = null;
     16    /**
     17     * Instance of the class
     18     *
     19     * @var Login|null
     20     */
     21    private static $instance = null;
    1622
    17     private function __construct()
    18     {
    19         add_shortcode(static::SHORTCODE_TAG, [$this, 'render']);
    20         add_action("login_form", function () {
    21             echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
    22         });
     23    /**
     24     * Login constructor.
     25     */
     26    private function __construct() {
     27        add_shortcode(static::SHORTCODE_TAG, [$this, 'render']);
     28        /**
     29         * If display on wp login page is enabled
     30         */
     31        if (AdminSettings::instance()->displayOnWPLoginPage()) {
     32            add_action('login_form', function () {
     33                echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
     34            });
     35        }
    2336
    24         add_action("woocommerce_login_form_end", function () {
    25             echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
    26         });
    27     }
     37        /**
     38         * If display on login form is enabled
     39         */
     40        if (AdminSettings::instance()->displayOnWoocommerceLoginForm()) {
     41            add_action('woocommerce_login_form_end', function () {
     42                echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
     43            });
     44        }
    2845
    29     public static function instance()
    30     {
    31         if (is_null(self::$instance)) {
    32             self::$instance = new self();
    33         }
     46    }
    3447
    35         return self::$instance;
    36     }
     48    /**
     49     * Returns instance ot the class
     50     *
     51     * @return Login|null
     52     */
     53    public static function instance() {
     54        if (is_null(self::$instance)) {
     55            self::$instance = new self();
     56        }
    3757
    38     public function render()
    39     {
    40         if (is_user_logged_in()) {
    41             return '';
    42         }
     58        return self::$instance;
     59    }
    4360
    44         $setting_values = get_option('wordthree_option');
    45         $redirectUrl = $setting_values['login_redirect_url'] ?? $setting_values['login_redirect_url'] ?: admin_url();
    46         $design = $setting_values['button_design'] ?? $setting_values['button_design'] ?: 'large';
    47         $design_wrap = ($design == 'compact') ? $design . '-wrap' : 'large-wrap';
    48         $button_color = $setting_values['button_color'] ?? $setting_values['button_color'] ?: 'light';
    49         $design_icon = '<span class="icon-metamask ' . $design . '">' . AdminSettings::metaMaskIcon() . '</span>';
    50         return '<div class="wt-metamask-btn wt-metamask-login ' . $design_wrap . '"><button type="button" data-redirect-url="' . $redirectUrl . '" class="wordthree-metamask-btn wordthree-metamask-login ' . $button_color . '">' . $design_icon . esc_html__('Login Via Metamask', 'wordthree') . '</button></div>';
    51     }
     61    /**
     62     * Render shortcode output
     63     *
     64     * @return string
     65     */
     66    public function render() {
     67        /**
     68         * Not necessary to display if user is logged in
     69         */
     70        if (is_user_logged_in()) {
     71            return '';
     72        }
     73
     74        /**
     75         * Login by metamask is disabled
     76         */
     77        if (!AdminSettings::instance()->enableLogin()) {
     78            return '';
     79        }
     80
     81        $redirectUrl  = AdminSettings::instance()->redirectUrl();
     82        $design       = AdminSettings::instance()->buttonDesign();
     83        $design_wrap  = ( 'compact' == $design ) ? $design . '-wrap' : 'large-wrap';
     84        $button_color = AdminSettings::instance()->buttonColor();
     85
     86        $design_icon = '<span class="icon-metamask ' . $design . '">' . AdminSettings::metaMaskIcon() . '</span>';
     87        return '<div class="wt-metamask-btn wt-metamask-login ' . $design_wrap . '"><button type="button" data-redirect-url="' . $redirectUrl . '" class="wordthree-metamask-btn wordthree-metamask-login ' . $button_color . '">' . $design_icon . esc_html__('Login Via Metamask', 'wordthree') . '</button></div>';
     88    }
    5289
    5390}
  • wordthree/trunk/src/Shortcodes/Register.php

    r2793538 r2862545  
    22
    33
    4 namespace WordThree\MetamaskAuth\Shortcodes;
     4namespace WordThree\Metamask\Shortcodes;
    55
     6use WordThree\Metamask\AdminSettings;
    67
    7 use WordThree\MetamaskAuth\AdminSettings;
     8class Register {
     9    /**
     10     * Shortcode tag
     11     *
     12     * @var string
     13     */
     14    const SHORTCODE_TAG = 'wordthree_metamask_register';
    815
    9 class Register
    10 {
    11     const SHORTCODE_TAG = 'wordthree_metamask_register';
    12     /**
    13      * @var Login|null
    14      */
    15     private static $instance = null;
     16    /**
     17     * Instance of this class
     18     *
     19     * @var Register|null
     20     */
     21    private static $instance = null;
    1622
    17     private function __construct()
    18     {
    19         add_shortcode(static::SHORTCODE_TAG, [$this, 'render']);
    20         add_action("register_form", function () {
    21             echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
    22         });
     23    /**
     24     * Register constructor.
     25     */
     26    private function __construct() {
     27        add_shortcode(static::SHORTCODE_TAG, [$this, 'render']);
     28        /**
     29         * If display on register page is enabled
     30         */
     31        if (AdminSettings::instance()->displayOnWPRegisterPage()) {
     32            add_action('register_form', function () {
     33                echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
     34            });
     35        }
    2336
    24         add_action("woocommerce_register_form_end", function () {
    25             echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
    26         });
     37        /**
     38         * If display on woocommerce register form is enabled
     39         */
     40        if (AdminSettings::instance()->displayOnWoocommerceRegisterForm()) {
     41            add_action('woocommerce_register_form_end', function () {
     42                echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
     43            });
     44        }
    2745
    28         add_action('woocommerce_after_checkout_registration_form', function () {
    29             echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
    30         });
    31     }
     46        /**
     47         * If registration by metamask is enabled on woocommerce checkout form is enabled
     48         */
     49        if (AdminSettings::instance()->displayOnWoocommerceCheckoutForm()) {
     50            add_action('woocommerce_after_checkout_registration_form', function () {
     51                echo do_shortcode('[' . static::SHORTCODE_TAG . ']');
     52            });
     53        }
     54    }
    3255
    33     public static function instance()
    34     {
    35         if (is_null(self::$instance)) {
    36             self::$instance = new self();
    37         }
     56    /**
     57     * Instance of the class
     58     *
     59     * @return Register|null
     60     */
     61    public static function instance() {
     62        if (is_null(self::$instance)) {
     63            self::$instance = new self();
     64        }
    3865
    39         return self::$instance;
    40     }
     66        return self::$instance;
     67    }
    4168
    42     public function render()
    43     {
    44         if (is_user_logged_in()) {
    45             return '';
    46         }
     69    /**
     70     * Render shortcode
     71     *
     72     * @return string
     73     */
     74    public function render() {
     75        /**
     76         * Not necessary to display if user is logged in
     77         */
     78        if (is_user_logged_in()) {
     79            return '';
     80        }
    4781
    48         $setting_values = get_option('wordthree_option');
    49         $redirectUrl = $setting_values['login_redirect_url'] ?? $setting_values['login_redirect_url'] ?: admin_url();
    50         $design = $setting_values['button_design'] ?? $setting_values['button_design'] ?: 'large';
    51         $design_wrap = ($design == 'compact') ? $design . '-wrap' : 'large-wrap';
    52         $button_color = $setting_values['button_color'] ?? $setting_values['button_color'] ?: 'light';
    53         $design_icon = '<span class="icon-metamask ' . $design . '">' . AdminSettings::metaMaskIcon() . '</span>';
    54         return '<div class="wt-metamask-btn wt-metamask-login ' . $design_wrap . '"><button type="button" data-redirect-url="' . $redirectUrl . '" class="wordthree-metamask-btn wordthree-metamask-register ' . $button_color . '">' . $design_icon . esc_html__('Register Via Metamask', 'wordthree') . '</button></div>';
    55     }
     82        /**
     83         * Enable registration is disabled
     84         */
     85        if (!AdminSettings::instance()->enableRegister()) {
     86            return '';
     87        }
     88
     89        $redirectUrl  = AdminSettings::instance()->redirectUrl();
     90        $design       = AdminSettings::instance()->buttonDesign();
     91        $design_wrap  = ( 'compact' == $design ) ? $design . '-wrap' : 'large-wrap';
     92        $button_color = AdminSettings::instance()->buttonColor();
     93        $design_icon  = '<span class="icon-metamask ' . $design . '">' . AdminSettings::metaMaskIcon() . '</span>';
     94        return '<div class="wt-metamask-btn wt-metamask-login ' . $design_wrap . '"><button type="button" data-redirect-url="' . $redirectUrl . '" class="wordthree-metamask-btn wordthree-metamask-register ' . $button_color . '">' . $design_icon . esc_html__('Register Via Metamask', 'wordthree') . '</button></div>';
     95    }
    5696}
  • wordthree/trunk/vendor/composer/autoload_classmap.php

    r2793538 r2862545  
    3131    'Elliptic\\Utils' => $vendorDir . '/simplito/elliptic-php/lib/Utils.php',
    3232    'Symfony\\Polyfill\\Mbstring\\Mbstring' => $vendorDir . '/symfony/polyfill-mbstring/Mbstring.php',
    33     'WordThree\\MetamaskAuth\\Activate' => $baseDir . '/src/Activate.php',
    34     'WordThree\\MetamaskAuth\\AdminSettings' => $baseDir . '/src/AdminSettings.php',
    35     'WordThree\\MetamaskAuth\\AuthManager' => $baseDir . '/src/AuthManager.php',
    36     'WordThree\\MetamaskAuth\\Metamask' => $baseDir . '/src/Metamask.php',
    37     'WordThree\\MetamaskAuth\\RestRoutes' => $baseDir . '/src/RestRoutes.php',
    38     'WordThree\\MetamaskAuth\\Shortcodes' => $baseDir . '/src/Shortcodes.php',
    39     'WordThree\\MetamaskAuth\\Shortcodes\\Link' => $baseDir . '/src/Shortcodes/Link.php',
    40     'WordThree\\MetamaskAuth\\Shortcodes\\Login' => $baseDir . '/src/Shortcodes/Login.php',
    41     'WordThree\\MetamaskAuth\\Shortcodes\\Register' => $baseDir . '/src/Shortcodes/Register.php',
     33    'WordThree\\Metamask\\Activate' => $baseDir . '/src/Activate.php',
     34    'WordThree\\Metamask\\AdminSettings' => $baseDir . '/src/AdminSettings.php',
     35    'WordThree\\Metamask\\AuthManager' => $baseDir . '/src/AuthManager.php',
     36    'WordThree\\Metamask\\Metamask' => $baseDir . '/src/Metamask.php',
     37    'WordThree\\Metamask\\RestRoutes' => $baseDir . '/src/RestRoutes.php',
     38    'WordThree\\Metamask\\Shortcodes' => $baseDir . '/src/Shortcodes.php',
     39    'WordThree\\Metamask\\Shortcodes\\Link' => $baseDir . '/src/Shortcodes/Link.php',
     40    'WordThree\\Metamask\\Shortcodes\\Login' => $baseDir . '/src/Shortcodes/Login.php',
     41    'WordThree\\Metamask\\Shortcodes\\Register' => $baseDir . '/src/Shortcodes/Register.php',
     42    'WordThree\\Metamask\\VerifyPersonalSignature' => $baseDir . '/src/VerifyPersonalSignature.php',
    4243    'kornrunner\\Keccak' => $vendorDir . '/kornrunner/keccak/src/Keccak.php',
    4344);
  • wordthree/trunk/vendor/composer/autoload_psr4.php

    r2793538 r2862545  
    88return array(
    99    'kornrunner\\' => array($vendorDir . '/kornrunner/keccak/src'),
    10     'WordThree\\MetamaskAuth\\' => array($baseDir . '/src'),
     10    'WordThree\\Metamask\\' => array($baseDir . '/src'),
    1111    'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
    1212    'Elliptic\\' => array($vendorDir . '/simplito/elliptic-php/lib'),
  • wordthree/trunk/vendor/composer/autoload_static.php

    r2793538 r2862545  
    1818        'W' =>
    1919        array (
    20             'WordThree\\MetamaskAuth\\' => 23,
     20            'WordThree\\Metamask\\' => 19,
    2121        ),
    2222        'S' =>
     
    4040            0 => __DIR__ . '/..' . '/kornrunner/keccak/src',
    4141        ),
    42         'WordThree\\MetamaskAuth\\' =>
     42        'WordThree\\Metamask\\' =>
    4343        array (
    4444            0 => __DIR__ . '/../..' . '/src',
     
    8787        'Elliptic\\Utils' => __DIR__ . '/..' . '/simplito/elliptic-php/lib/Utils.php',
    8888        'Symfony\\Polyfill\\Mbstring\\Mbstring' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/Mbstring.php',
    89         'WordThree\\MetamaskAuth\\Activate' => __DIR__ . '/../..' . '/src/Activate.php',
    90         'WordThree\\MetamaskAuth\\AdminSettings' => __DIR__ . '/../..' . '/src/AdminSettings.php',
    91         'WordThree\\MetamaskAuth\\AuthManager' => __DIR__ . '/../..' . '/src/AuthManager.php',
    92         'WordThree\\MetamaskAuth\\Metamask' => __DIR__ . '/../..' . '/src/Metamask.php',
    93         'WordThree\\MetamaskAuth\\RestRoutes' => __DIR__ . '/../..' . '/src/RestRoutes.php',
    94         'WordThree\\MetamaskAuth\\Shortcodes' => __DIR__ . '/../..' . '/src/Shortcodes.php',
    95         'WordThree\\MetamaskAuth\\Shortcodes\\Link' => __DIR__ . '/../..' . '/src/Shortcodes/Link.php',
    96         'WordThree\\MetamaskAuth\\Shortcodes\\Login' => __DIR__ . '/../..' . '/src/Shortcodes/Login.php',
    97         'WordThree\\MetamaskAuth\\Shortcodes\\Register' => __DIR__ . '/../..' . '/src/Shortcodes/Register.php',
     89        'WordThree\\Metamask\\Activate' => __DIR__ . '/../..' . '/src/Activate.php',
     90        'WordThree\\Metamask\\AdminSettings' => __DIR__ . '/../..' . '/src/AdminSettings.php',
     91        'WordThree\\Metamask\\AuthManager' => __DIR__ . '/../..' . '/src/AuthManager.php',
     92        'WordThree\\Metamask\\Metamask' => __DIR__ . '/../..' . '/src/Metamask.php',
     93        'WordThree\\Metamask\\RestRoutes' => __DIR__ . '/../..' . '/src/RestRoutes.php',
     94        'WordThree\\Metamask\\Shortcodes' => __DIR__ . '/../..' . '/src/Shortcodes.php',
     95        'WordThree\\Metamask\\Shortcodes\\Link' => __DIR__ . '/../..' . '/src/Shortcodes/Link.php',
     96        'WordThree\\Metamask\\Shortcodes\\Login' => __DIR__ . '/../..' . '/src/Shortcodes/Login.php',
     97        'WordThree\\Metamask\\Shortcodes\\Register' => __DIR__ . '/../..' . '/src/Shortcodes/Register.php',
     98        'WordThree\\Metamask\\VerifyPersonalSignature' => __DIR__ . '/../..' . '/src/VerifyPersonalSignature.php',
    9899        'kornrunner\\Keccak' => __DIR__ . '/..' . '/kornrunner/keccak/src/Keccak.php',
    99100    );
  • wordthree/trunk/vendor/composer/installed.php

    r2793538 r2862545  
    11<?php return array(
    22    'root' => array(
    3         'pretty_version' => '1.0.0+no-version-set',
    4         'version' => '1.0.0.0',
     3        'pretty_version' => 'dev-main',
     4        'version' => 'dev-main',
    55        'type' => 'library',
    66        'install_path' => __DIR__ . '/../../',
    77        'aliases' => array(),
    8         'reference' => NULL,
     8        'reference' => '19d3a600e4cfd3e6a9ec7fc8430fcb2dd1bee11b',
    99        'name' => 'wordthree/metamask-auth',
    1010        'dev' => true,
     
    5757        ),
    5858        'wordthree/metamask-auth' => array(
    59             'pretty_version' => '1.0.0+no-version-set',
    60             'version' => '1.0.0.0',
     59            'pretty_version' => 'dev-main',
     60            'version' => 'dev-main',
    6161            'type' => 'library',
    6262            'install_path' => __DIR__ . '/../../',
    6363            'aliases' => array(),
    64             'reference' => NULL,
     64            'reference' => '19d3a600e4cfd3e6a9ec7fc8430fcb2dd1bee11b',
    6565            'dev_requirement' => false,
    6666        ),
  • wordthree/trunk/views/popup.php

    r2793538 r2862545  
    11<div id="wordthree-confirm-box" style="display: none">
    2     <div class="popup">
    3         <p class="wt-message"></p>
    4         <button class="btn-yes">YES</button>
    5         <button class="btn-cancel">CANCEL</button>
    6     </div>
     2    <div class="popup">
     3        <p class="wt-message"></p>
     4        <button class="btn-yes"><?php esc_html_e('YES', 'wordthree'); ?></button>
     5        <button class="btn-cancel"><?php esc_html_e('CANCEL', 'wordthree'); ?></button>
     6    </div>
    77</div>
    88<div class="wordthree-confirm-overlay"></div>
     9
     10<div class="wordthree-overlay" style="display: none">
     11    <div class="wordthree-ellipsis"><div></div><div></div><div></div><div></div></div>
     12</div>
  • wordthree/trunk/wordthree.php

    r2793583 r2862545  
    44 * Plugin URI: https://www.wordthree.co.uk
    55 * Description: Authenticate and Register Users with MetaMask.
    6  * Version: 1.0.0
     6 * Version: 1.1.0
    77 * Author: cudedesign
    88 * Author URI: https://www.cudedesign.co.uk
     9 * Requires PHP: 7.3
    910 * Text Domain: wordthree
    1011 **/
    1112
    12 use WordThree\MetamaskAuth\Metamask;
     13use WordThree\Metamask\Activate;
     14use WordThree\Metamask\Metamask;
    1315
    14 define('WORDTHREE_METAMASK_PLUGIN_FILE', __FILE__);
    15 define('WORDTHREE_METAMASK_PLUGIN_PATH', plugin_dir_path(__FILE__));
    16 define('WORDTHREE_METAMASK_PLUGIN_URL', plugin_dir_url(__FILE__));
    17 define('WORDTHREE_METAMASK_PLUGIN_VERSION', '1.0.0');
     16require_once plugin_dir_path(__FILE__) . 'src/Activate.php';
     17register_activation_hook(__FILE__, [Activate::class, 'activate']);
    1818
    19 require_once(WORDTHREE_METAMASK_PLUGIN_PATH . 'vendor/autoload.php');
     19add_action('plugins_loaded', function () {
     20    if (!function_exists('is_plugin_active')) {
     21        include_once ABSPATH . 'wp-admin/includes/plugin.php';
     22    }
    2023
    21 $wordThree = Metamask::instance();
     24    if (!is_plugin_active('wordthree-pro/wordthree.php')) {
     25        define('WORDTHREE_METAMASK_PLUGIN_PATH', plugin_dir_path(__FILE__));
     26        define('WORDTHREE_METAMASK_PLUGIN_URL', plugin_dir_url(__FILE__));
     27        define('WORDTHREE_METAMASK_PLUGIN_VERSION', '1.0.1');
     28
     29        require_once WORDTHREE_METAMASK_PLUGIN_PATH . 'vendor/autoload.php';
     30
     31        Metamask::instance();
     32    }
     33});
Note: See TracChangeset for help on using the changeset viewer.